feliking

Inicial

Showing 85 changed files with 4333 additions and 0 deletions
# Created by https://www.gitignore.io/api/node,webstorm,visualstudiocode,macos,windows,linux
### Linux ###
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### macOS ###
*.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Typescript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
### WebStorm ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
# Sensitive or high-churn files:
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.xml
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
# Gradle:
.idea/**/gradle.xml
.idea/**/libraries
# Mongo Explorer plugin:
.idea/**/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### WebStorm Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
.idea/sonarlint
### Windows ###
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
# End of https://www.gitignore.io/api/node,webstorm,visualstudiocode,macos,windows,linux
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/sequelize-pg-generator.iml" filepath="$PROJECT_DIR$/.idea/sequelize-pg-generator.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.tmp" />
<excludeFolder url="file://$MODULE_DIR$/temp" />
<excludeFolder url="file://$MODULE_DIR$/tmp" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
---------------------------------------
<a name="History"></a>
History & Release Notes
=======================
Note
----
Version history for minimal documentation updates are not listed here to prevent cluttering.
###### 0.9.0
* Added: sequelize-types are added. (pg-structure deprecated it.)
###### 0.8.0 / 2015-10-14
* Added: `alias.json` file is generated in target directory to let developer easily override relationship names.
###### 0.7.0 / 2015-10-14
* Changed: Location of utils.js is changed to inside of model directory.
###### 0.6.0 / 2015-09-10
* -t --templateName parameter added to spgen. This name is used to choose one of the builtin template directories.
* sequalize4 template added for protect backward compatibility.
* sequalize4 template supports object references property. (references and referencesKey will be depreciated in Sequelize 4)
###### 0.5.4 / 2015-06-16
* pg-structure updated to latest version.
###### 0.5.3 / 2015-06-16
* Added: JSONB support and Boolean default value. Contributed by viniciuspinto (https://github.com/viniciuspinto)
###### 0.4.2 / 2015-04-27
* Added documentation and examples.
###### 0.3.1 / 2015-01-10
* Tested for Sequelize 2.0 RC7
###### 0.3.0 / 2014-12-30
* Removed: pg-native dependency removed. Some users experienced problems during install.
* Added: generate.addRelationNameToManyToMany configuration to prefix relation aliases prevent further name clashes which cannot be prevented by generate.addTableNameToManyToMany. Default: true.
* Added: generate.stripFirstTableNameFromManyToMany configuration added. Default: true
* Changed: generate.addTableNameToManyToMany configuration default is false now.
* Changed: Default naming rule for many to many relations.
* Added: Logging uses Winston module now.
* Added: Doc update for Windows OS users.
* Fixed: Database tables without any column throws error when warning configuration is true.
###### 0.2.0 / 2014-12-27
* Added: Automatic alias and naming validations to prevent name clash.
* Added: generate.addTableNameToManyToMany configuration to prefix relation aliases prevent name clash. Default: true.
* Added: --throwError option added to CLI. This option decides wheter to throw error or simply log.
* Added: Prevent hasMany through and belongsToMany true at the same time.
* Fixed: generate.prefixForBelongsTo aliases are not properly camel cased.
* Fixed: --resetConfig option does not work from CLI
* Doc update
###### 0.1.17 / 2014-12-26
* Fixed: CLI command does not work.
* Added: Required parameters warning.
###### 0.1.15 / 2014-12-26
* Added: Turkish documentation added.
* Fixed: Typos and mistakes in documents.
###### 0.1.12 / 2014-12-23
* Added: Tests added.
* Added: --nolog option added to spgen command.
* Added: --resetConfig option. Also details and caveat added to the document.
* Fix: lib/index.js exported function expects different parameters than written in documentation.
* Fix: Command line arguments fixed.
* Fix: Data type variable name configuration is ignored.
* Document update.
###### 0.1.0 / 2014-12-23
* Initial version.
The MIT License (MIT)
Copyright (c) 2014 Özüm Eldoğan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
REPORTER = list
test:
clear
echo Starting test *********************************************************
./node_modules/mocha/bin/mocha
echo Ending test
doc:
clear
echo Starting JSDOC *********************************************************
jsdoc -c jsdoc-conf.json README-JSDOC.md
echo Creating README.md *****************************************************
rm -f README.md
jsdoc2md --src lib/index.js template/utils.js template/index.js >>JSDOC.md
cat README-JSDOC.md JSDOC.md History.md LICENSE > README.md
cat README-JSDOC-TR.md JSDOC.md History.md LICENSE > README-TR.md
rm -r -f JSDOC.md
.PHONY: test doc
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
/*jslint node: true, nomen: true*/
"use strict";
var path = require('path');
module.exports = {
"sequelize-pg-generator": {
"database": {
"host": "127.0.0.1",
"port": 5432,
"user": "user",
"password": "password",
"database": "",
"schema": ["public"]
},
"template": {
"engine": "swig",
"extension": "html",
"folder": path.join(__dirname, '..', 'template', 'default')
},
"output": {
"log": true,
"folder": "../../../src/infraestructure/model",
"beautify": true,
"indent": 2,
"preserveNewLines": false,
"warning": true
},
"generate": {
"stripFirstTableFromHasMany": true,
"addTableNameToManyToMany": false,
"addRelationNameToManyToMany": true,
"stripFirstTableNameFromManyToMany": true,
"hasManyThrough": false,
"belongsToMany": true,
"prefixForBelongsTo": "related",
"useSchemaName": false,
"modelCamelCase": true,
"relationAccessorCamelCase": true,
"columnAccessorCamelCase": false,
"columnDefault": false,
"columnDescription": true,
"columnAutoIncrement": true,
"tableDescription": true,
"dataTypeVariable": "DataTypes",
"skipTable": []
},
"tableOptions": {
"timestamps": false
}
}
};
This diff is collapsed. Click to expand it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>sequelize-pg-generator Classes</title>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">
<link type="text/css" rel="stylesheet" href="styles/site.cerulean.css">
</head>
<body>
<div class="container-fluid">
<div class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<a class="brand" href="index.html">sequelize-pg-generator</a>
<ul class="nav">
<li class="dropdown">
<a href="modules.list.html" class="dropdown-toggle" data-toggle="dropdown">Modules<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li>
<a href="module-lib_index.html">lib/index</a>
</li>
<li>
<a href="module-path_to_model.html">path/to/model</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li>
<a href="GeneratorUtil.html">GeneratorUtil</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="row-fluid">
<div class="span8">
<div id="main">
<h1 class="page-title">Classes</h1>
<section>
<header>
<h2>
</h2>
</header>
<article>
<div class="container-overview">
<dl class="details">
</dl>
</div>
<h3 class="subsection-title">Classes</h3>
<dl>
<dt><a href="GeneratorUtil.html">GeneratorUtil</a></dt>
<dd></dd>
</dl>
</article>
</section>
</div>
<div class="clearfix"></div>
<footer>
<span class="copyright">
sequelize-pg-generator Copyright © 2014 Özüm Eldoğan.
</span>
<br />
<span class="jsdoc-message">
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.0-dev</a>
on Fri Nov 27th 2015 using the <a
href="https://github.com/terryweiss/docstrap">DocStrap template</a>.
</span>
</footer>
</div>
<div class="span3">
<div id="toc"></div>
</div>
<br clear="both">
</div>
</div>
<!--<script src="scripts/sunlight.js"></script>-->
<script src="scripts/docstrap.lib.js"></script>
<script src="scripts/bootstrap-dropdown.js"></script>
<script src="scripts/toc.js"></script>
<script>
$( function () {
$( "[id*='$']" ).each( function () {
var $this = $( this );
$this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) );
} );
$( "#toc" ).toc( {
anchorName : function ( i, heading, prefix ) {
return $( heading ).attr( "id" ) || ( prefix + i );
},
selectors : "h1,h2,h3,h4",
showAndHide : false,
scrollTo : "100px"
} );
$( "#toc>ul" ).addClass( "nav nav-pills nav-stacked" );
$( "#main span[id^='toc']" ).addClass( "toc-shim" );
$( '.dropdown-toggle' ).dropdown();
// $( ".tutorial-section pre, .readme-section pre" ).addClass( "sunlight-highlight-javascript" ).addClass( "linenums" );
$( ".tutorial-section pre, .readme-section pre" ).each( function () {
var $this = $( this );
var example = $this.find( "code" );
exampleText = example.html();
var lang = /{@lang (.*?)}/.exec( exampleText );
if ( lang && lang[1] ) {
exampleText = exampleText.replace( lang[0], "" );
example.html( exampleText );
lang = lang[1];
} else {
lang = "javascript";
}
if ( lang ) {
$this
.addClass( "sunlight-highlight-" + lang )
.addClass( "linenums" )
.html( example.html() );
}
} );
Sunlight.highlightAll( {
lineNumbers : true,
showMenu : true,
enableDoclinks : true
} );
} );
</script>
<!--Navigation and Symbol Display-->
<!--Google Analytics-->
</body>
</html>
\ No newline at end of file
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>sequelize-pg-generator Modules</title>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">
<link type="text/css" rel="stylesheet" href="styles/site.cerulean.css">
</head>
<body>
<div class="container-fluid">
<div class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<a class="brand" href="index.html">sequelize-pg-generator</a>
<ul class="nav">
<li class="dropdown">
<a href="modules.list.html" class="dropdown-toggle" data-toggle="dropdown">Modules<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li>
<a href="module-lib_index.html">lib/index</a>
</li>
<li>
<a href="module-path_to_model.html">path/to/model</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li>
<a href="GeneratorUtil.html">GeneratorUtil</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="row-fluid">
<div class="span8">
<div id="main">
<h1 class="page-title">Modules</h1>
<section>
<header>
<h2>
</h2>
</header>
<article>
<div class="container-overview">
<dl class="details">
</dl>
</div>
<h3 class="subsection-title">Classes</h3>
<dl>
<dt><a href="GeneratorUtil.html">GeneratorUtil</a></dt>
<dd></dd>
</dl>
</article>
</section>
</div>
<div class="clearfix"></div>
<footer>
<span class="copyright">
sequelize-pg-generator Copyright © 2014 Özüm Eldoğan.
</span>
<br />
<span class="jsdoc-message">
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.0-dev</a>
on Fri Nov 27th 2015 using the <a
href="https://github.com/terryweiss/docstrap">DocStrap template</a>.
</span>
</footer>
</div>
<div class="span3">
<div id="toc"></div>
</div>
<br clear="both">
</div>
</div>
<!--<script src="scripts/sunlight.js"></script>-->
<script src="scripts/docstrap.lib.js"></script>
<script src="scripts/bootstrap-dropdown.js"></script>
<script src="scripts/toc.js"></script>
<script>
$( function () {
$( "[id*='$']" ).each( function () {
var $this = $( this );
$this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) );
} );
$( "#toc" ).toc( {
anchorName : function ( i, heading, prefix ) {
return $( heading ).attr( "id" ) || ( prefix + i );
},
selectors : "h1,h2,h3,h4",
showAndHide : false,
scrollTo : "100px"
} );
$( "#toc>ul" ).addClass( "nav nav-pills nav-stacked" );
$( "#main span[id^='toc']" ).addClass( "toc-shim" );
$( '.dropdown-toggle' ).dropdown();
// $( ".tutorial-section pre, .readme-section pre" ).addClass( "sunlight-highlight-javascript" ).addClass( "linenums" );
$( ".tutorial-section pre, .readme-section pre" ).each( function () {
var $this = $( this );
var example = $this.find( "code" );
exampleText = example.html();
var lang = /{@lang (.*?)}/.exec( exampleText );
if ( lang && lang[1] ) {
exampleText = exampleText.replace( lang[0], "" );
example.html( exampleText );
lang = lang[1];
} else {
lang = "javascript";
}
if ( lang ) {
$this
.addClass( "sunlight-highlight-" + lang )
.addClass( "linenums" )
.html( example.html() );
}
} );
Sunlight.highlightAll( {
lineNumbers : true,
showMenu : true,
enableDoclinks : true
} );
} );
</script>
<!--Navigation and Symbol Display-->
<!--Google Analytics-->
</body>
</html>
\ No newline at end of file
This diff is collapsed. Click to expand it.
/* ============================================================
* bootstrap-dropdown.js v2.3.2
* http://getbootstrap.com/2.3.2/javascript.html#dropdowns
* ============================================================
* Copyright 2013 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================ */
!function ($) {
"use strict"; // jshint ;_;
/* DROPDOWN CLASS DEFINITION
* ========================= */
var toggle = '[data-toggle=dropdown]'
, Dropdown = function (element) {
var $el = $(element).on('click.dropdown.data-api', this.toggle)
$('html').on('click.dropdown.data-api', function () {
$el.parent().removeClass('open')
})
}
Dropdown.prototype = {
constructor: Dropdown
, toggle: function (e) {
var $this = $(this)
, $parent
, isActive
if ($this.is('.disabled, :disabled')) return
$parent = getParent($this)
isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement) {
// if mobile we we use a backdrop because click events don't delegate
$('<div class="dropdown-backdrop"/>').insertBefore($(this)).on('click', clearMenus)
}
$parent.toggleClass('open')
}
$this.focus()
return false
}
, keydown: function (e) {
var $this
, $items
, $active
, $parent
, isActive
, index
if (!/(38|40|27)/.test(e.keyCode)) return
$this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
$parent = getParent($this)
isActive = $parent.hasClass('open')
if (!isActive || (isActive && e.keyCode == 27)) {
if (e.which == 27) $parent.find(toggle).focus()
return $this.click()
}
$items = $('[role=menu] li:not(.divider):visible a', $parent)
if (!$items.length) return
index = $items.index($items.filter(':focus'))
if (e.keyCode == 38 && index > 0) index-- // up
if (e.keyCode == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items
.eq(index)
.focus()
}
}
function clearMenus() {
$('.dropdown-backdrop').remove()
$(toggle).each(function () {
getParent($(this)).removeClass('open')
})
}
function getParent($this) {
var selector = $this.attr('data-target')
, $parent
if (!selector) {
selector = $this.attr('href')
selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
$parent = selector && $(selector)
if (!$parent || !$parent.length) $parent = $this.parent()
return $parent
}
/* DROPDOWN PLUGIN DEFINITION
* ========================== */
var old = $.fn.dropdown
$.fn.dropdown = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('dropdown')
if (!data) $this.data('dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
$.fn.dropdown.Constructor = Dropdown
/* DROPDOWN NO CONFLICT
* ==================== */
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
/* APPLY TO STANDARD DROPDOWN ELEMENTS
* =================================== */
$(document)
.on('click.dropdown.data-api', clearMenus)
.on('click.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.dropdown.data-api' , toggle, Dropdown.prototype.toggle)
.on('keydown.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown)
}(window.jQuery);
/* ========================================================
* bootstrap-tab.js v2.3.0
* http://twitter.github.com/bootstrap/javascript.html#tabs
* ========================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* TAB CLASS DEFINITION
* ==================== */
var Tab = function (element) {
this.element = $(element)
}
Tab.prototype = {
constructor: Tab
, show: function () {
var $this = this.element
, $ul = $this.closest('ul:not(.dropdown-menu)')
, selector = $this.attr('data-target')
, previous
, $target
, e
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
if ( $this.parent('li').hasClass('active') ) return
previous = $ul.find('.active:last a')[0]
e = $.Event('show', {
relatedTarget: previous
})
$this.trigger(e)
if (e.isDefaultPrevented()) return
$target = $(selector)
this.activate($this.parent('li'), $ul)
this.activate($target, $target.parent(), function () {
$this.trigger({
type: 'shown'
, relatedTarget: previous
})
})
}
, activate: function ( element, container, callback) {
var $active = container.find('> .active')
, transition = callback
&& $.support.transition
&& $active.hasClass('fade')
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if ( element.parent('.dropdown-menu') ) {
element.closest('li.dropdown').addClass('active')
}
callback && callback()
}
transition ?
$active.one($.support.transition.end, next) :
next()
$active.removeClass('in')
}
}
/* TAB PLUGIN DEFINITION
* ===================== */
var old = $.fn.tab
$.fn.tab = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('tab')
if (!data) $this.data('tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
$.fn.tab.Constructor = Tab
/* TAB NO CONFLICT
* =============== */
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
/* TAB DATA-API
* ============ */
$(document).on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
e.preventDefault()
$(this).tab('show')
})
}(window.jQuery);
\ No newline at end of file
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
PR.registerLangHandler(PR.createSimpleLexer([
["pln", /^[\t\n\f\r ]+/, null, " \t\r\n "]
], [
["str", /^"(?:[^\n\f\r"\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*"/, null],
["str", /^'(?:[^\n\f\r'\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*'/, null],
["lang-css-str", /^url\(([^"')]*)\)/i],
["kwd", /^(?:url|rgb|!important|@import|@page|@media|@charset|inherit)(?=[^\w-]|$)/i, null],
["lang-css-kw", /^(-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*)\s*:/i],
["com", /^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//],
["com", /^(?:<\!--|--\>)/],
["lit", /^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],
["lit", /^#[\da-f]{3,6}/i],
["pln", /^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i],
["pun", /^[^\s\w"']+/]
]), ["css"]);
PR.registerLangHandler(PR.createSimpleLexer([], [
["kwd", /^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i]
]), ["css-kw"]);
PR.registerLangHandler(PR.createSimpleLexer([], [
["str", /^[^"')]+/]
]), ["css-str"]);
\ No newline at end of file
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
(function($) {
$.fn.toc = function(options) {
var self = this;
var opts = $.extend({}, jQuery.fn.toc.defaults, options);
var container = $(opts.container);
var headings = $(opts.selectors, container);
var headingOffsets = [];
var activeClassName = opts.prefix+'-active';
var scrollTo = function(e) {
if (opts.smoothScrolling) {
e.preventDefault();
var elScrollTo = $(e.target).attr('href');
var $el = $(elScrollTo);
$('body,html').animate({ scrollTop: $el.offset().top }, 400, 'swing', function() {
location.hash = elScrollTo;
});
}
$('li', self).removeClass(activeClassName);
$(e.target).parent().addClass(activeClassName);
};
//highlight on scroll
var timeout;
var highlightOnScroll = function(e) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
var top = $(window).scrollTop(),
highlighted;
for (var i = 0, c = headingOffsets.length; i < c; i++) {
if (headingOffsets[i] >= top) {
$('li', self).removeClass(activeClassName);
highlighted = $('li:eq('+(i-1)+')', self).addClass(activeClassName);
opts.onHighlight(highlighted);
break;
}
}
}, 50);
};
if (opts.highlightOnScroll) {
$(window).bind('scroll', highlightOnScroll);
highlightOnScroll();
}
return this.each(function() {
//build TOC
var el = $(this);
var ul = $('<ul/>');
headings.each(function(i, heading) {
var $h = $(heading);
headingOffsets.push($h.offset().top - opts.highlightOffset);
//add anchor
var anchor = $('<span/>').attr('id', opts.anchorName(i, heading, opts.prefix)).insertBefore($h);
//build TOC item
var a = $('<a/>')
.text(opts.headerText(i, heading, $h))
.attr('href', '#' + opts.anchorName(i, heading, opts.prefix))
.bind('click', function(e) {
scrollTo(e);
el.trigger('selected', $(this).attr('href'));
});
var li = $('<li/>')
.addClass(opts.itemClass(i, heading, $h, opts.prefix))
.append(a);
ul.append(li);
});
el.html(ul);
});
};
jQuery.fn.toc.defaults = {
container: 'body',
selectors: 'h1,h2,h3',
smoothScrolling: true,
prefix: 'toc',
onHighlight: function() {},
highlightOnScroll: true,
highlightOffset: 100,
anchorName: function(i, heading, prefix) {
return prefix+i;
},
headerText: function(i, heading, $heading) {
return $heading.text();
},
itemClass: function(i, heading, $heading, prefix) {
return prefix + '-' + $heading[0].tagName.toLowerCase();
}
};
})(jQuery);
This diff is collapsed. Click to expand it.
/* Tomorrow Theme */
/* Original theme - https://github.com/chriskempson/tomorrow-theme */
/* Pretty printing styles. Used with prettify.js. */
/* SPAN elements with the classes below are added by prettyprint. */
/* plain text */
.pln {
color: #4d4d4c; }
@media screen {
/* string content */
.str {
color: #718c00; }
/* a keyword */
.kwd {
color: #8959a8; }
/* a comment */
.com {
color: #8e908c; }
/* a type name */
.typ {
color: #4271ae; }
/* a literal value */
.lit {
color: #f5871f; }
/* punctuation */
.pun {
color: #4d4d4c; }
/* lisp open bracket */
.opn {
color: #4d4d4c; }
/* lisp close bracket */
.clo {
color: #4d4d4c; }
/* a markup tag name */
.tag {
color: #c82829; }
/* a markup attribute name */
.atn {
color: #f5871f; }
/* a markup attribute value */
.atv {
color: #3e999f; }
/* a declaration */
.dec {
color: #f5871f; }
/* a variable name */
.var {
color: #c82829; }
/* a function name */
.fun {
color: #4271ae; } }
/* Use higher contrast and text-weight for printable form. */
@media print, projection {
.str {
color: #060; }
.kwd {
color: #006;
font-weight: bold; }
.com {
color: #600;
font-style: italic; }
.typ {
color: #404;
font-weight: bold; }
.lit {
color: #044; }
.pun, .opn, .clo {
color: #440; }
.tag {
color: #006;
font-weight: bold; }
.atn {
color: #404; }
.atv {
color: #060; } }
/* Style */
/*
pre.prettyprint {
background: white;
font-family: Menlo, Monaco, Consolas, monospace;
font-size: 12px;
line-height: 1.5;
border: 1px solid #ccc;
padding: 10px; }
*/
/* Specify class=linenums on a pre to get line numbering */
ol.linenums {
margin-top: 0;
margin-bottom: 0; }
/* IE indents via margin-left */
li.L0,
li.L1,
li.L2,
li.L3,
li.L4,
li.L5,
li.L6,
li.L7,
li.L8,
li.L9 {
/* */ }
/* Alternate shading for lines */
li.L1,
li.L3,
li.L5,
li.L7,
li.L9 {
/* */ }
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
/* global styles */
.sunlight-container {
clear: both !important;
position: relative !important;
margin: 10px 0 !important;
}
.sunlight-code-container {
clear: both !important;
position: relative !important;
border: none;
border-color: #626262 !important;
background-color: #262626 !important;
}
.sunlight-highlighted, .sunlight-container, .sunlight-container textarea {
font-family: Consolas, Inconsolata, Monaco, "Courier New" !important;
font-size: 12px !important;
line-height: 15px !important;
}
.sunlight-highlighted, .sunlight-container textarea {
color: #FFFFFF !important;
margin: 0 !important;
}
.sunlight-container textarea {
padding-left: 0 !important;
margin-left: 0 !important;
margin-right: 0 !important;
padding-right: 0 !important;
}
.sunlight-code-container > .sunlight-highlighted {
white-space: pre;
overflow-x: auto;
overflow-y: hidden; /* ie requires this wtf? */
}
.sunlight-highlighted {
z-index: 1;
position: relative;
}
.sunlight-highlighted * {
background: transparent;
}
.sunlight-line-number-margin {
float: left !important;
margin-right: 5px !important;
margin-top: 0 !important;
margin-bottom: 0 !important;
padding: 0 !important;
padding-right: 4px !important;
padding-left: 4px !important;
border-right: 1px solid #9A9A9A !important;
background-color: #3E3E3E !important;
color: #9A9A9A !important;
text-align: right !important;
position: relative;
z-index: 3;
}
.sunlight-highlighted a, .sunlight-line-number-margin a {
border: none !important;
text-decoration: none !important;
font-style: normal !important;
padding: 0 !important;
}
.sunlight-line-number-margin a {
color: inherit !important;
}
.sunlight-line-highlight-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
z-index: 0;
}
.sunlight-line-highlight-overlay div {
height: 15px;
width: 100%;
}
.sunlight-line-highlight-overlay .sunlight-line-highlight-active {
background-color: #4B4B4B;
}
/* menu */
.sunlight-menu {
background-color: #FFFFCC;
color: #000000;
}
.sunlight-menu ul {
margin: 0 !important;
padding: 0 !important;
list-style-type: none !important;
}
.sunlight-menu li {
float: right !important;
margin-left: 5px !important;
}
.sunlight-menu a, .sunlight-menu img {
color: #000099 !important;
text-decoration: none !important;
border: none !important;
}
.sunlight-string,
.sunlight-char,
.sunlight-heredoc,
.sunlight-heredocDeclaration,
.sunlight-nowdoc,
.sunlight-longString,
.sunlight-rawString,
.sunlight-binaryString,
.sunlight-verbatimString,
.sunlight-rawLongString,
.sunlight-binaryLongString,
.sunlight-diff .sunlight-added {
color: #55EB54 !important;
}
.sunlight-operator,
.sunlight-punctuation,
.sunlight-delimiter {
color: #B1EDEC !important;
}
.sunlight-ident,
.sunlight-diff .sunlight-unchanged {
color: #E0E0E0 !important;
font-weight: bold !important;
}
.sunlight-comment,
.sunlight-xmlDocCommentContent,
.sunlight-nginx .sunlight-ssiCommand,
.sunlight-sln .sunlight-formatDeclaration,
.sunlight-diff .sunlight-mergeHeader,
.sunlight-diff .sunlight-noNewLine {
color: #787D31 !important;
}
.sunlight-number,
.sunlight-cdata,
.sunlight-guid,
.sunlight-diff .sunlight-modified {
color: #F7BA7E !important;
font-weight: bold !important;
}
.sunlight-named-ident,
.sunlight-xml .sunlight-attribute,
.sunlight-constant,
.sunlight-javascript .sunlight-globalVariable,
.sunlight-globalObject,
.sunlight-css .sunlight-id,
.sunlight-python .sunlight-attribute,
.sunlight-nginx .sunlight-context,
.sunlight-httpd .sunlight-context,
.sunlight-lisp .sunlight-declarationSpecifier,
.sunlight-erlang .sunlight-userDefinedFunction,
.sunlight-diff .sunlight-removed {
color: #FBBDEE !important;
font-weight: bold !important;
}
.sunlight-keyword,
.sunlight-languageConstruct,
.sunlight-specialOperator,
.sunlight-xml .sunlight-tagName,
.sunlight-xml .sunlight-operator,
.sunlight-bash .sunlight-command,
.sunlight-erlang .sunlight-moduleAttribute {
color: #A3CCF7 !important;
font-weight: bold !important;
}
.sunlight-shortOpenTag,
.sunlight-openTag,
.sunlight-closeTag,
.sunlight-xmlOpenTag,
.sunlight-xmlCloseTag,
.sunlight-aspOpenTag,
.sunlight-aspCloseTag,
.sunlight-label,
.sunlight-css .sunlight-importantFlag {
background-color: #7373C1 !important;
}
.sunlight-content {
color: #FFFFFF !important;
font-weight: bold !important;
}
.sunlight-function,
.sunlight-globalFunction,
.sunlight-objective-c .sunlight-messageDestination,
.sunlight-ruby .sunlight-specialFunction,
.sunlight-6502asm .sunlight-illegalOpcode,
.sunlight-powershell .sunlight-switch,
.sunlight-lisp .sunlight-macro,
.sunlight-lisp .sunlight-specialForm,
.sunlight-lisp .sunlight-type,
.sunlight-sln .sunlight-sectionName,
.sunlight-diff .sunlight-header {
color: #C8BBF1 !important;
font-weight: bold !important;
}
.sunlight-variable,
.sunlight-environmentVariable,
.sunlight-specialVariable,
.sunlight-objective-c .sunlight-messageArgumentName,
.sunlight-lisp .sunlight-globalVariable,
.sunlight-ruby .sunlight-globalVariable,
.sunlight-ruby .sunlight-instanceVariable {
color: #F5E5B0 !important;
font-weight: bold !important;
}
.sunlight-regexLiteral,
.sunlight-lisp .sunlight-operator,
.sunlight-6502asm .sunlight-pseudoOp,
.sunlight-erlang .sunlight-macro,
.sunlight-diff .sunlight-rangeInfo {
color: #E0F16A !important;
}
.sunlight-specialVariable {
font-style: italic !important;
font-weight: bold !important;
}
.sunlight-csharp .sunlight-pragma,
.sunlight-preprocessorDirective,
.sunlight-vb .sunlight-compilerDirective {
color: #666363 !important;
font-style: italic !important;
}
.sunlight-xmlDocCommentMeta,
.sunlight-java .sunlight-annotation,
.sunlight-scala .sunlight-annotation,
.sunlight-docComment {
color: #666363 !important;
}
.sunlight-quotedIdent,
.sunlight-ruby .sunlight-subshellCommand,
.sunlight-lisp .sunlight-keywordArgument,
.sunlight-haskell .sunlight-infixOperator,
.sunlight-erlang .sunlight-quotedAtom {
color: #F8CA16 !important;
}
/* html/xml */
.sunlight-xml .sunlight-tagName,
.sunlight-xml .sunlight-operator,
.sunlight-xml .sunlight-attribute {
font-weight: normal !important;
}
.sunlight-doctype {
color: #DEB9B2 !important;
font-style: italic !important;
}
.sunlight-xml .sunlight-entity {
background-color: #E6E585 !important;
color: #000000 !important;
}
/* javascript */
.sunlight-javascript .sunlight-reservedWord {
font-style: italic !important;
}
/* css */
.sunlight-css .sunlight-element {
color: #E9EE97 !important;
}
.sunlight-css .sunlight-microsoftFilterPrefix {
color: #C9FF9F !important;
}
.sunlight-css .sunlight-rule {
color: #0099FF !important;
}
.sunlight-css .sunlight-class {
color: #E78282 !important;
}
.sunlight-css .sunlight-pseudoClass, .sunlight-css .sunlight-pseudoElement {
color: #73D693 !important;
}
/* bash */
.sunlight-bash .sunlight-hashBang {
color: #FFFF00 !important;
}
.sunlight-bash .sunlight-verbatimCommand {
color: #BBA4EE !important;
}
.sunlight-bash .sunlight-variable,
.sunlight-bash .sunlight-specialVariable {
color: #ED8585 !important;
}
/* python */
.sunlight-python .sunlight-specialMethod {
font-weight: bold !important;
color: #B0A3C2;
}
/* ruby */
.sunlight-ruby .sunlight-symbol {
font-weight: bold !important;
color: #90EEA2 !important;
}
/* brainfuck */
.sunlight-brainfuck {
font-weight: bold !important;
color: #000000 !important;
}
.sunlight-brainfuck .sunlight-increment {
background-color: #FF9900 !important;
}
.sunlight-brainfuck .sunlight-decrement {
background-color: #FF99FF !important;
}
.sunlight-brainfuck .sunlight-incrementPointer {
background-color: #FFFF99 !important;
}
.sunlight-brainfuck .sunlight-decrementPointer {
background-color: #66CCFF !important;
}
.sunlight-brainfuck .sunlight-read {
background-color: #FFFFFF !important;
}
.sunlight-brainfuck .sunlight-write {
background-color: #99FF99 !important;
}
.sunlight-brainfuck .sunlight-openLoop, .sunlight-brainfuck .sunlight-closeLoop {
background-color: #FFFFFF !important;
}
/* 6502 asm */
.sunlight-6502asm .sunlight-label {
background: none !important;
color: #FFFFFF !important;
text-decoration: underline !important;
}
/* lisp */
.sunlight-lisp .sunlight-macro {
font-style: italic !important;
}
/* erlang */
.sunlight-erlang .sunlight-atom {
color: #FFFFFF !important;
font-weight: bold !important;
}
\ No newline at end of file
/* global styles */
.sunlight-container {
clear: both !important;
position: relative !important;
margin: 10px 0 !important;
}
.sunlight-code-container {
clear: both !important;
position: relative !important;
border: none;
border-color: #969696 !important;
background-color: #FFFFFF !important;
}
.sunlight-highlighted, .sunlight-container, .sunlight-container textarea {
font-family: Consolas, Inconsolata, Monaco, "Courier New" !important;
font-size: 12px !important;
line-height: 15px !important;
}
.sunlight-highlighted, .sunlight-container textarea {
color: #000000 !important;
margin: 0 !important;
}
.sunlight-container textarea {
padding-left: 0 !important;
margin-left: 0 !important;
margin-right: 0 !important;
padding-right: 0 !important;
}
.sunlight-code-container > .sunlight-highlighted {
white-space: pre;
overflow-x: auto;
overflow-y: hidden; /* ie requires this wtf? */
}
.sunlight-highlighted {
z-index: 1;
position: relative;
}
.sunlight-highlighted * {
background: transparent;
}
.sunlight-line-number-margin {
float: left !important;
margin-right: 5px !important;
margin-top: 0 !important;
margin-bottom: 0 !important;
padding: 0 !important;
padding-right: 4px !important;
padding-left: 4px !important;
border-right: 1px solid #CCCCCC !important;
background-color: #EEEEEE !important;
color: #848484 !important;
text-align: right !important;
position: relative;
z-index: 3;
}
.sunlight-highlighted a, .sunlight-line-number-margin a {
border: none !important;
text-decoration: none !important;
font-weight: normal !important;
font-style: normal !important;
padding: 0 !important;
}
.sunlight-line-number-margin a {
color: inherit !important;
}
.sunlight-line-highlight-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
z-index: 0;
}
.sunlight-line-highlight-overlay div {
height: 15px;
width: 100%;
}
.sunlight-line-highlight-overlay .sunlight-line-highlight-active {
background-color: #E7FCFA;
}
/* menu */
.sunlight-menu {
background-color: #FFFFCC;
color: #000000;
}
.sunlight-menu ul {
margin: 0 !important;
padding: 0 !important;
list-style-type: none !important;
}
.sunlight-menu li {
float: right !important;
margin-left: 5px !important;
}
.sunlight-menu a, .sunlight-menu img {
color: #000099 !important;
text-decoration: none !important;
border: none !important;
}
.sunlight-string,
.sunlight-char,
.sunlight-heredoc,
.sunlight-heredocDeclaration,
.sunlight-nowdoc,
.sunlight-longString,
.sunlight-rawString,
.sunlight-binaryString,
.sunlight-rawLongString,
.sunlight-binaryLongString,
.sunlight-verbatimString,
.sunlight-diff .sunlight-removed {
color: #990000 !important;
}
.sunlight-ident,
.sunlight-operator,
.sunlight-punctuation,
.sunlight-delimiter,
.sunlight-diff .sunlight-unchanged {
color: #000000 !important;
}
.sunlight-comment,
.sunlight-xmlDocCommentContent,
.sunlight-nginx .sunlight-ssiCommand,
.sunlight-sln .sunlight-formatDeclaration,
.sunlight-diff .sunlight-added {
color: #009900 !important;
}
.sunlight-number,
.sunlight-guid,
.sunlight-cdata {
color: #CC6600 !important;
}
.sunlight-named-ident,
.sunlight-constant,
.sunlight-javascript .sunlight-globalVariable,
.sunlight-globalObject,
.sunlight-python .sunlight-attribute,
.sunlight-nginx .sunlight-context,
.sunlight-httpd .sunlight-context,
.sunlight-haskell .sunlight-class,
.sunlight-haskell .sunlight-type,
.sunlight-lisp .sunlight-declarationSpecifier,
.sunlight-erlang .sunlight-userDefinedFunction,
.sunlight-diff .sunlight-header {
color: #2B91AF !important;
}
.sunlight-keyword,
.sunlight-languageConstruct,
.sunlight-css
.sunlight-element,
.sunlight-bash .sunlight-command,
.sunlight-specialOperator,
.sunlight-erlang .sunlight-moduleAttribute,
.sunlight-xml .sunlight-tagName,
.sunlight-xml .sunlight-operator,
.sunlight-diff .sunlight-modified {
color: #0000FF !important;
}
.sunlight-shortOpenTag,
.sunlight-openTag,
.sunlight-closeTag,
.sunlight-xmlOpenTag,
.sunlight-xmlCloseTag,
.sunlight-aspOpenTag,
.sunlight-aspCloseTag,
.sunlight-label,
.sunlight-css .sunlight-importantFlag {
background-color: #FFFF99 !important;
color: #000000 !important;
}
.sunlight-function,
.sunlight-globalFunction,
.sunlight-ruby .sunlight-specialFunction,
.sunlight-objective-c .sunlight-messageDestination,
.sunlight-6502asm .sunlight-illegalOpcode,
.sunlight-powershell .sunlight-switch,
.sunlight-lisp .sunlight-macro,
.sunlight-lisp .sunlight-specialForm,
.sunlight-lisp .sunlight-type,
.sunlight-sln .sunlight-sectionName,
.sunlight-diff .sunlight-rangeInfo {
color: #B069AF !important;
}
.sunlight-variable,
.sunlight-specialVariable,
.sunlight-environmentVariable,
.sunlight-objective-c .sunlight-messageArgumentName,
.sunlight-lisp .sunlight-globalVariable,
.sunlight-ruby .sunlight-globalVariable,
.sunlight-ruby .sunlight-instanceVariable,
.sunlight-sln .sunlight-operator {
color: #325484 !important;
}
.sunlight-regexLiteral,
.sunlight-lisp .sunlight-operator,
.sunlight-6502asm .sunlight-pseudoOp,
.sunlight-erlang .sunlight-macro {
color: #FF00B2 !important;
}
.sunlight-specialVariable {
font-style: italic !important;
font-weight: bold !important;
}
.sunlight-csharp .sunlight-pragma,
.sunlight-preprocessorDirective,
.sunlight-vb .sunlight-compilerDirective,
.sunlight-diff .sunlight-mergeHeader,
.sunlight-diff .sunlight-noNewLine {
color: #999999 !important;
font-style: italic !important;
}
.sunlight-xmlDocCommentMeta,
.sunlight-java .sunlight-annotation,
.sunlight-scala .sunlight-annotation,
.sunlight-docComment {
color: #808080 !important;
}
.sunlight-quotedIdent,
.sunlight-ruby .sunlight-subshellCommand,
.sunlight-lisp .sunlight-keywordArgument,
.sunlight-haskell .sunlight-infixOperator,
.sunlight-erlang .sunlight-quotedAtom {
color: #999900 !important;
}
/* xml */
.sunlight-xml .sunlight-string {
color: #990099 !important;
}
.sunlight-xml .sunlight-attribute {
color: #FF0000 !important;
}
.sunlight-xml .sunlight-entity {
background-color: #EEEEEE !important;
color: #000000 !important;
border: 1px solid #000000 !important;
}
.sunlight-xml .sunlight-doctype {
color: #2B91AF !important;
}
/* javascript */
.sunlight-javascript .sunlight-reservedWord {
font-style: italic !important;
}
/* css */
.sunlight-css .sunlight-microsoftFilterPrefix {
color: #FF00FF !important;
}
.sunlight-css .sunlight-rule {
color: #0099FF !important;
}
.sunlight-css .sunlight-keyword {
color: #4E65B8 !important;
}
.sunlight-css .sunlight-class {
color: #FF0000 !important;
}
.sunlight-css .sunlight-id {
color: #8A8E13 !important;
}
.sunlight-css .sunlight-pseudoClass,
.sunlight-css .sunlight-pseudoElement {
color: #368B87 !important;
}
/* bash */
.sunlight-bash .sunlight-hashBang {
color: #3D97F5 !important;
}
.sunlight-bash .sunlight-verbatimCommand {
color: #999900 !important;
}
.sunlight-bash .sunlight-variable,
.sunlight-bash .sunlight-specialVariable {
color: #FF0000 !important;
}
/* python */
.sunlight-python .sunlight-specialMethod {
font-weight: bold !important;
color: #A07DD3;
}
/* ruby */
.sunlight-ruby .sunlight-symbol {
font-weight: bold !important;
color: #ED7272 !important;
}
/* brainfuck */
.sunlight-brainfuck {
font-weight: bold !important;
color: #000000 !important;
}
.sunlight-brainfuck .sunlight-increment {
background-color: #FF9900 !important;
}
.sunlight-brainfuck .sunlight-decrement {
background-color: #FF99FF !important;
}
.sunlight-brainfuck .sunlight-incrementPointer {
background-color: #FFFF99 !important;
}
.sunlight-brainfuck .sunlight-decrementPointer {
background-color: #66CCFF !important;
}
.sunlight-brainfuck .sunlight-read {
background-color: #FFFFFF !important;
}
.sunlight-brainfuck .sunlight-write {
background-color: #99FF99 !important;
}
.sunlight-brainfuck .sunlight-openLoop, .sunlight-brainfuck .sunlight-closeLoop {
background-color: #FFFFFF !important;
}
/* 6502 asm */
.sunlight-6502asm .sunlight-label {
font-weight: bold !important;
color: #000000 !important;
background: none !important;
}
/* lisp */
.sunlight-lisp .sunlight-macro {
font-style: italic !important;
}
/* erlang */
.sunlight-erlang .sunlight-atom {
font-weight: bold !important;
}
\ No newline at end of file
This diff is collapsed. Click to expand it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>sequelize-pg-generator Source: template/index.js</title>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">
<link type="text/css" rel="stylesheet" href="styles/site.cerulean.css">
</head>
<body>
<div class="container-fluid">
<div class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<a class="brand" href="index.html">sequelize-pg-generator</a>
<ul class="nav">
<li class="dropdown">
<a href="modules.list.html" class="dropdown-toggle" data-toggle="dropdown">Modules<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li>
<a href="module-lib_index.html">lib/index</a>
</li>
<li>
<a href="module-path_to_model.html">path/to/model</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li>
<a href="GeneratorUtil.html">GeneratorUtil</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<div id="main">
<h1 class="page-title">Source: template/index.js</h1>
<section>
<article>
<pre
class="sunlight-highlight-javascript linenums">/**
* This file is auto generated by sequelize-pg-generator.
* @module path/to/model
* @author Özüm Eldoğan
*/
/*jslint node: true, stupid: true, nomen: true */
"use strict";
var Sequelize = require('sequelize'),
fs = require('fs'),
path = require('path'),
util = require('util'),
models = {},
relationships = {},
modelsPath = '',
definitionDir = 'definition-files',
definitionDirCustom = definitionDir + '-custom',
debug = false,
debugFD = '',
sequelize = null;
/**
* Requires given npm module file and defines sequelize module according to exported object from that module.
* @private
* @param {string} file - Location of the npm module file which contains model definition.
*/
function defineModel(file) {
var object = require(file),
options = object.options || {},
modelName = object.modelName;
fs.writeSync(debugFD, 'var ' + modelName + ' = Sequelize.define("' + modelName + '",\n' + util.inspect(object.attributes) + ',\n' + util.inspect(options, {depth: null}) + ');\n\n\n');
models[modelName] = sequelize.define(modelName, object.attributes, options);
if (object.relations !== undefined) {
relationships[modelName] = object.relations;
}
}
/**
* Define 'hasMany' and 'belongsTo' relations.
* @private
* @param {string} modelName - Name of the model
* @param {string} relationType - Type of the relation 'hasMany' or 'belongsTo'
* @param {string} targetModelName - Name of the target model which this relation related to.
* @param {Object} options - Sequelize options of relation.
*/
function defineRelation(modelName, relationType, targetModelName, options) {
fs.writeSync(debugFD, modelName + '.' + relationType + '(' + targetModelName + ', ' + util.inspect(options, {depth: null}) + ');\n\n');
models[modelName][relationType](models[targetModelName], options); // account.hasMany(contact, {...})
}
/**
* Generates list of definition files by looking given modelsPath directory. It traverses 'definition-files'
* and 'definition-files-custom' directories to generate the list. Files in 'definition-files' will be skipped
* if a file with same name is found in 'definition-files-custom' directory.
* @private
* @returns {Array}
* @example
* var list = getFileList('../model'); // ['./definition-files-custom/public_cart.js', './definition-files/public_account.js]
*/
function getFileList() {
var i, file, isOverridden = {}, files = [], customFiles, baseFiles;
baseFiles = fs.readdirSync(path.join(modelsPath, definitionDir));
customFiles = fs.readdirSync(path.join(modelsPath, definitionDirCustom));
for (i = 0; i &lt; customFiles.length; i = i + 1) {
file = customFiles[i];
if (file.match(/\.js$/)) {
isOverridden[file] = true;
files.push('./' + path.join(definitionDirCustom, file));
}
}
for (i = 0; i &lt; baseFiles.length; i = i + 1) {
file = baseFiles[i];
if (!isOverridden[file] &amp;&amp; file.match(/\.js$/)) {
files.push('./' + path.join(definitionDir, file));
}
}
return files;
}
/**
* Iterates all relations and executes given callback on them. Callback is passed
* ({string} modelName, {string} relationType, {string} targetModelName, {Object} relationOptions)
* @private
* @param {function} callback - Callback function.
* @returns {Array}
*/
function processAllRelations(callback) {
var i, modelName, relation, relations, result = [];
for (modelName in relationships) {
if (relationships.hasOwnProperty(modelName)) {
relations = relationships[modelName];
for (i = 0; i &lt; relations.length; i = i + 1) {
relation = relations[i];
result.push(callback(modelName, relation.type, relation.model, relation.details));
}
}
}
return result;
}
/**
* Initializes models.
* @private
*/
function init() {
var debugFile = path.join(__dirname, 'debug.js');
if (fs.existsSync(debugFile)) { fs.unlinkSync(debugFile); }
debugFD = fs.openSync(debugFile, 'a');
getFileList(modelsPath).forEach(defineModel);
processAllRelations(defineRelation);
fs.closeSync(debugFD);
}
module.exports = {};
/**
* Sets up sequelize models based on model files in given directory for given database details.
* @param {string} database - Name of the database to connect
* @param {string} username - Username of the database
* @param {string} password - Password of the database
* @param {Object} obj - Object to pass new Sequelize() function. See Sequelize for details.
* @example
* var orm = require('../model');
* orm.setup('path/to/model', 'database', 'user', 'password', {
* host: '127.0.0.1',
* logging: false,
* native: true
* });
*/
module.exports.setup = function (database, username, password, obj) {
if (typeof obj !== 'object') { obj = {}; }
if (obj.dialect === undefined || obj.dialect === null) { obj.dialect = 'postgres'; }
if (arguments.length === 2) {
sequelize = new Sequelize(database, username);
} else if (arguments.length === 3) {
sequelize = new Sequelize(database, username, password);
} else if (arguments.length === 4) {
sequelize = new Sequelize(database, username, password, obj);
}
modelsPath = __dirname;
init();
};
/**
* Returns requested model with given name.
* @param {string} name - Model name
* @returns {object} - Sequelize model
*/
module.exports.model = function (name) {
return models[name];
};
/**
* Returns Sequelize object.
* @returns {Sequelize} - Sequelize object
*/
module.exports.Sequelize = function () {
return Sequelize;
};
/**
* Returns sequelize instance.
* @returns {Sequelize} - sequelize instance
*/
module.exports.sequelize = function () {
return sequelize;
};
</pre>
</article>
</section>
</div>
<div class="clearfix"></div>
<footer>
<span class="copyright">
sequelize-pg-generator Copyright © 2014 Özüm Eldoğan.
</span>
<br />
<span class="jsdoc-message">
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.3.1</a>
on Mon Aug 3rd 2015 using the <a
href="https://github.com/terryweiss/docstrap">DocStrap template</a>.
</span>
</footer>
</div>
<br clear="both">
</div>
</div>
<!--<script src="scripts/sunlight.js"></script>-->
<script src="scripts/docstrap.lib.js"></script>
<script src="scripts/bootstrap-dropdown.js"></script>
<script src="scripts/toc.js"></script>
<script>
$( function () {
$( "[id*='$']" ).each( function () {
var $this = $( this );
$this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) );
} );
$( "#toc" ).toc( {
anchorName : function ( i, heading, prefix ) {
return $( heading ).attr( "id" ) || ( prefix + i );
},
selectors : "h1,h2,h3,h4",
showAndHide : false,
scrollTo : "100px"
} );
$( "#toc>ul" ).addClass( "nav nav-pills nav-stacked" );
$( "#main span[id^='toc']" ).addClass( "toc-shim" );
$( '.dropdown-toggle' ).dropdown();
// $( ".tutorial-section pre, .readme-section pre" ).addClass( "sunlight-highlight-javascript" ).addClass( "linenums" );
$( ".tutorial-section pre, .readme-section pre" ).each( function () {
var $this = $( this );
var example = $this.find( "code" );
exampleText = example.html();
var lang = /{@lang (.*?)}/.exec( exampleText );
if ( lang && lang[1] ) {
exampleText = exampleText.replace( lang[0], "" );
example.html( exampleText );
lang = lang[1];
} else {
lang = "javascript";
}
if ( lang ) {
$this
.addClass( "sunlight-highlight-" + lang )
.addClass( "linenums" )
.html( example.html() );
}
} );
Sunlight.highlightAll( {
lineNumbers : true,
showMenu : true,
enableDoclinks : true
} );
} );
</script>
<!--Navigation and Symbol Display-->
<!--Google Analytics-->
</body>
</html>
This diff is collapsed. Click to expand it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>sequelize-pg-generator Source: template/utils.js</title>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">
<link type="text/css" rel="stylesheet" href="styles/site.cerulean.css">
</head>
<body>
<div class="container-fluid">
<div class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<a class="brand" href="index.html">sequelize-pg-generator</a>
<ul class="nav">
<li class="dropdown">
<a href="modules.list.html" class="dropdown-toggle" data-toggle="dropdown">Modules<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li>
<a href="module-lib_index.html">lib/index</a>
</li>
<li>
<a href="module-path_to_model.html">path/to/model</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li>
<a href="GeneratorUtil.html">GeneratorUtil</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<div id="main">
<h1 class="page-title">Source: template/utils.js</h1>
<section>
<article>
<pre
class="sunlight-highlight-javascript linenums">/**
* Utility methods to modify and customize auto generated models without affecting further auto generations.
* Require this module from model customization scripts located in path/to/model/definitions-files-custom directory.
* @class
* @author Özüm Eldoğan
*/
/*jslint node: true */
"use strict";
/**
* @constructor
* @param model
*/
var GeneratorUtil = function (model) {
this.model = model;
};
/**
* Searches and returns relation with the given alias. Alias is defined in sequelize options with parameter 'as'
* @method
* @param {string} as - Alias of the relation.
* @returns {Object}
*/
GeneratorUtil.prototype.getRelation = function (as) {
var i,
relations = this.model.relations;
for (i = 0; i &lt; relations.length; i = i + 1) {
if (relations[i].details.as === as) {
return relations[i];
}
}
};
/**
* Searches and returns attribute with the given alias. Alias is defined in sequelize options with parameter 'as'
* @method
* @param {string} name - Name of the attribute.
* @returns {Object}
*/
GeneratorUtil.prototype.getAttribute = function (name) {
return this.model.attributes[name];
};
/**
* Searches and returns attribute with the given alias. Alias is defined in sequelize options with parameter 'as'
* @method
* @param {string} oldName - Name of the attribute which it's name to be changed.
* @param {string} newName - New name of the attribute.
* @throws Will throw error if there is already an attribute with new name exists or attribute with oldName does not exists.
*/
GeneratorUtil.prototype.renameAttribute = function (oldName, newName) {
if (this.model.attributes[newName] !== undefined) {
throw new Error('There is already an attribute with the same name ("' + newName + '") in table "' + this.model.modelName + '".');
}
if (this.model.attributes[oldName] === undefined) {
throw new Error('There is no attribute with the name "' + oldName + '". in table "' + this.model.modelName + '".');
}
this.model.attributes[newName] = this.model.attributes[oldName];
delete this.model.attributes[oldName];
};
/**
* Creates and returns new object with utility functions.
* @param model
* @returns {GeneratorUtil}
*/
module.exports = function (model) {
return new GeneratorUtil(model);
};
</pre>
</article>
</section>
</div>
<div class="clearfix"></div>
<footer>
<span class="copyright">
sequelize-pg-generator Copyright © 2014 Özüm Eldoğan.
</span>
<br />
<span class="jsdoc-message">
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.0-dev</a>
on Fri Nov 27th 2015 using the <a
href="https://github.com/terryweiss/docstrap">DocStrap template</a>.
</span>
</footer>
</div>
<br clear="both">
</div>
</div>
<!--<script src="scripts/sunlight.js"></script>-->
<script src="scripts/docstrap.lib.js"></script>
<script src="scripts/bootstrap-dropdown.js"></script>
<script src="scripts/toc.js"></script>
<script>
$( function () {
$( "[id*='$']" ).each( function () {
var $this = $( this );
$this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) );
} );
$( "#toc" ).toc( {
anchorName : function ( i, heading, prefix ) {
return $( heading ).attr( "id" ) || ( prefix + i );
},
selectors : "h1,h2,h3,h4",
showAndHide : false,
scrollTo : "100px"
} );
$( "#toc>ul" ).addClass( "nav nav-pills nav-stacked" );
$( "#main span[id^='toc']" ).addClass( "toc-shim" );
$( '.dropdown-toggle' ).dropdown();
// $( ".tutorial-section pre, .readme-section pre" ).addClass( "sunlight-highlight-javascript" ).addClass( "linenums" );
$( ".tutorial-section pre, .readme-section pre" ).each( function () {
var $this = $( this );
var example = $this.find( "code" );
exampleText = example.html();
var lang = /{@lang (.*?)}/.exec( exampleText );
if ( lang && lang[1] ) {
exampleText = exampleText.replace( lang[0], "" );
example.html( exampleText );
lang = lang[1];
} else {
lang = "javascript";
}
if ( lang ) {
$this
.addClass( "sunlight-highlight-" + lang )
.addClass( "linenums" )
.html( example.html() );
}
} );
Sunlight.highlightAll( {
lineNumbers : true,
showMenu : true,
enableDoclinks : true
} );
} );
</script>
<!--Navigation and Symbol Display-->
<!--Google Analytics-->
</body>
</html>
{
"opts": {
"template": "node_modules/ink-docstrap/template",
"encoding": "utf8",
"destination": "./doc/",
"recurse": true,
"private": false
},
"tags": {
"allowUnknownTags": true
},
"source": {
"include": ["lib","template"],
"includePattern": ".+\\.js(doc)?$",
"excludePattern": "(^|\\/|\\\\)_"
},
"plugins" : ["plugins/markdown"],
"i18n": {
"locale": "<en_US|tr_TR>",
"extension": ".js"
},
"templates" : {
"cleverLinks" : false,
"monospaceLinks" : false,
"dateFormat" : "ddd MMM Do YYYY",
"outputSourceFiles" : true,
"outputSourcePath" : true,
"systemName" : "sequelize-pg-generator",
"footer" : "",
"copyright" : "sequelize-pg-generator Copyright © 2014 Özüm Eldoğan.",
"navType" : "vertical",
"theme" : "cerulean",
"linenums" : true,
"collapseSymbols" : false,
"inverseNav" : true,
"highlightTutorialCode" : true
},
"markdown" : {
"parser" : "gfm",
"hardwrap" : true
}
}
\ No newline at end of file
/**
* @private
*/
/*jslint node: true, nomen: true, regexp: true */
"use strict";
if (!String.prototype.quote) {
// oop version - no dependencies
String.prototype.quote = (function () {
// prepare fallback
// ----------------
// backslash escape double quotes and backslashes
var escp_regex = /[\\"]/g,
escp_callback = '\\$&',
// escape control characters
ctrl_map = {
'\b': '\\b', // backspace
'\t': '\\t', // tab
'\n': '\\n', // new line
'\f': '\\f', // form feed
'\r': '\\r' // carriage return
},
// don't rely on `Object.keys(ctrl_map).join('')`
ctrl_regex = new RegExp('[\b\t\n\f\r]', 'g'),
ctrl_callback = function (match) {
return ctrl_map[match];
},
// hex-escape, spare out control characters and ASCII printables
// [0-7,11,14-31,127-255]
xhex_regex = /[\x00-\x07\x0B\x0E-\x1F\x7F-\xFF]/g,
xhex_callback = function (match, char_code) {
char_code = match.charCodeAt(0);
return '\\x' + (char_code < 16 ? '0' : '') + char_code;
},
// hex-escape all others
uhex_regex = /[\u0100-\uFFFF]/g,
uhex_callback = function (match, char_code) {
char_code = match.charCodeAt(0);
return '\\u' + (char_code < 4096 ? '0' : '') + char_code;
},
// delegate to native `JSON.stringify` if available
stringify = typeof JSON !== 'undefined' && JSON.stringify;
// return actual polyfill
// ----------------------
return function () {
var self = this; // promote compression
if (self === null) { throw new TypeError('can\'t convert ' + self + ' to object'); }
if (stringify) { return stringify(self); }
return '"' + self
.replace(escp_regex, escp_callback)
.replace(ctrl_regex, ctrl_callback)
.replace(xhex_regex, xhex_callback)
.replace(uhex_regex, uhex_callback) + '"';
};
}());
// generic version - requires Function#bind
String.quote = Function.call.bind(''.quote);
}
\ No newline at end of file
#!/usr/bin/env node
/*jslint node: true */
"use strict";
var program = require('commander'),
generator = require('../index.js'),
version = require('../../package.json').version,
options = {};
/**
* Parses CSV and returns as a list.
* @private
* @param {string} val - CSV values.
* @returns {Array}
*/
function list(val) {
return val.split(',');
}
// Define options, help text
program
.version(version)
.option('-h, --host [host]', 'IP address or host name of the database server')
.option(' --port [port]', 'Port of database server to connect')
.option('-d, --database [database]', 'Database name')
.option('-u, --user [user]', 'Username to connect to database')
.option('-p, --password [password]', 'Password to connect to database')
.option('-s, --schema [schema]', 'Comma separated names of the database schemas. i.e public,extra_schema', list)
.option('-o, --output [output]', 'Output folder')
.option('-c, --config [config]', 'Path of the configuration file')
.option('-t --templateName [templateName]','Use builtin template folder with given name. (default|sequelize4)')
.option(' --nolog', 'No log output')
.option(' --resetConfig', 'Reset configuration. (Side-step. Not for production.)')
.option(' --throwError', 'Instead of logging errors to console, throws error.')
;
program.on('--help', function(){
console.log(' Connects given PostgreSQL database and generates Sequelize models');
console.log(' automatically. Can be customized via node-config.');
console.log('');
console.log(' Examples:');
console.log('');
console.log(' $ %s -h 127.0.0.1 -d our_crm -u george -p topSeCRet -s public,extra -o ./model', process.argv[0]);
console.log(' $ %s -c ../config/default.json -u natalie -p topSecret', process.argv[0]);
console.log('');
});
program.parse(process.argv);
// Show help if no arguments are present.
if (process.argv.length === 2) { program.help(); }
// Copy all options to options global variable to override config.
['host', 'port', 'database', 'user', 'password', 'schema', 'output', 'config', 'templateName', 'nolog', 'resetConfig', 'throwError'].forEach(
function(option) {
if (program[option] !== undefined) {
options[option] = program[option];
}
}
);
if (program.templateName === undefined) {
console.warn(
'\n********************************************************************************************\n' +
'DEPRECIATION WARNING:\n' +
'You should use either use -t or provide a template folder in your configuration.\n' +
'Default value for template folder will be not provided to support future Sequelize versions.\n' +
'********************************************************************************************\n'
);
}
generator(function (err) {
if (err) {
if ( options.throwError ) {
throw(err);
} else {
console.log(err);
}
}
process.exit(0);
}, options);
\ No newline at end of file
This diff is collapsed. Click to expand it.
/**
* @author Özüm Eldoğan
*/
/*jslint node: true */
"use strict";
// PostgreSQL Enum type comes as user-defined. As a result it should be handled manually.
module.exports = {
'array' : { type: '.ARRAY' },
'bigint' : { type: '.BIGINT', hasLength: true },
'bigserial' : { type: '.BIGINT', hasLength: true },
'bit' : { type: '.CHAR', hasLength: true }, // Not directly supported in Sequelize
'bit varying' : { type: '.STRING', hasLength: true }, // Not directly supported in Sequelize
'boolean' : { type: '.BOOLEAN' },
'box' : { type: '.STRING', hasLength: true }, // Not directly supported in Sequelize
'bytea' : { type: '.BLOB' },
'character' : { type: '.CHAR', hasLength: true },
'character varying' : { type: '.STRING', hasLength: true },
'cidr' : { type: '.STRING', hasLength: true }, // Not directly supported in Sequelize
'circle' : { type: '.STRING', hasLength: true }, // Not directly supported in Sequelize
'date' : { type: '.DATEONLY' },
'double precision' : { type: '.FLOAT', hasPrecision: true },
'hstore' : { type: '.HSTORE' },
'inet' : { type: '.STRING', hasLength: true }, // Not directly supported in Sequelize
'integer' : { type: '.INTEGER', hasLength: true },
'interval' : { type: '.STRING', hasLength: true }, // Not directly supported in Sequelize
'json' : { type: '.JSON' },
'jsonb' : { type: '.JSONB' },
'line' : { type: '.STRING', hasLength: true }, // Not directly supported in Sequelize
'lseg' : { type: '.STRING', hasLength: true }, // Not directly supported in Sequelize
'macaddr' : { type: '.STRING', hasLength: true }, // Not directly supported in Sequelize
'money' : { type: '.DECIMAL', hasPrecision: true },
'numeric' : { type: '.DECIMAL', hasPrecision: true },
'path' : { type: '.STRING', hasLength: true }, // Not directly supported in Sequelize
'point' : { type: '.STRING', hasLength: true }, // Not directly supported in Sequelize
'polygon' : { type: '.STRING', hasLength: true }, // Not directly supported in Sequelize
'real' : { type: '.FLOAT', hasPrecision: true },
'smallint' : { type: '.INTEGER', hasLength: true },
'smallserial' : { type: '.INTEGER', hasLength: true },
'serial' : { type: '.INTEGER', hasLength: true },
'text' : { type: '.TEXT' },
'time without time zone' : { type: '.TIME' },
'time with time zone' : { type: '.TIME' },
'timestamp without time zone' : { type: '.DATE' },
'timestamp with time zone' : { type: '.DATE' },
'tsquery' : { type: '.STRING', hasLength: true }, // Not directly supported in Sequelize
'tsvector' : { type: '.STRING', hasLength: true }, // Not directly supported in Sequelize
'txid_snapshot' : { type: '.STRING', hasLength: true }, // Not directly supported in Sequelize
'uuid' : { type: '.UUID' },
'xml' : { type: '.STRING', hasLength: true }, // Not directly supported in Sequelize
'user-defined' : { type: '.STRING', hasLength: true } // Not directly supported in Sequelize
};
This diff is collapsed. Click to expand it.
{
"name": "sequelize-pg-generator",
"version": "0.9.3",
"description": "Auto Create Sequelize ORM Models from PostgreSQL.",
"main": "index.js",
"bin": {
"spgen": "lib/bin/spgen.js"
},
"scripts": {
"test": "make test"
},
"keywords": [
"postgresql",
"pg",
"postgres",
"database",
"schema",
"model",
"schema",
"export",
"dump",
"etl",
"erd",
"migration",
"transform",
"extract",
"information_schema",
"sequelize",
"orm",
"model",
"structure",
"auto generate",
"meta"
],
"author": {
"name": "Özüm Eldoğan"
},
"repository": {
"type": "git",
"url": "https://github.com/ozum/sequelize-pg-generator.git"
},
"license": "MIT",
"devDependencies": {
"chai": "^1.10.0",
"ink-docstrap": "^0.4.12",
"mocha": "^2.1.0",
"pg": "^4.1.1",
"pg-hstore": "^2.3.2",
"sequelize": "^3.1.1"
},
"dependencies": {
"async": "^0.9.0",
"commander": "^2.5.1",
"config": "^1.8.1",
"consolidate": "^0.10.0",
"ejs": "^1.0.0",
"fs-extra": "^0.13.0",
"inflection": "^1.5.1",
"js-beautify": "^1.5.4",
"json-stable-stringify": "^1.0.0",
"lodash": "^2.4.1",
"pg-hstore": "^2.3.2",
"pg-structure": "^1.11.3",
"swig": "^1.4.2",
"winston": "^0.8.3"
},
"readmeFilename": "README.md",
"bugs": {
"url": "https://github.com/ozum/sequelize-pg-generator/issues"
},
"homepage": "https://github.com/ozum/sequelize-pg-generator",
"_id": "sequelize-pg-generator@0.1.0",
"_shasum": "4a9deecd8712210defedf25a69548281547363d8",
"_from": "."
}
{% autoescape false %}
{{ column.accessorName }}: {
type: {{ column.type }}
{{ ifTrue('field', column.name) }}
{{ ifTrue('primaryKey', column.primaryKey) }}
{{ ifTrue('autoIncrement', column.autoIncrement) }}
{{ ifFalse('allowNull', column.allowNull) }}
{{ ifNotUndefined('defaultValue', column.defaultValue) }}
{{ ifTrue('unique', column.unique) }}
{{ ifTrue('comment', column.comment) }}
{{ ifTrue('references', column.references) }}
{{ ifTrue('referencesKey', column.referencesKey) }}
{{ ifTrue('onUpdate', column.onUpdate) }}
{{ ifTrue('onDelete', column.onDelete) }}
}
{% endautoescape %}
{% autoescape false %}
/*jslint node: true */
"use strict";
{%- if warning %}
/*------------------------------------------------------------------------------------
DO NOT EDIT THIS FILE !!! It is generated automatically and will be overwritten.
To modify this model:
1. Create '{{ table.baseFileName }}.js' file in 'definition-files-custom' directory located in this file's parent directory.
2. Copy the code below and paste it into '{{ table.baseFileName }}.js'.
3. Use utility methods to easily access orm properties.
"use strict";
var orm = require('{{mainScript}}'),
model = require('./{{ table.baseFileName }}.js'),
util = require('../utils.js')(model),
Seq = orm.Sequelize();
module.exports = model;
// Some utility methods:
{% if table.relations|first %}util.getRelation({{ table.relations|first.as }}).onDelete = 'CASCADE'; {% endif %}
{% if table.columns|first %}util.getAttribute({{table.columns|first.accessorName}}).comment = 'This is the comment'; {% endif %}
------------------------------------------------------------------------------------*/
{%- endif %}
{% macro ifTrue(label, value) %}
{% if value %}
,{{ label }}: {{ value }}
{% endif %}
{% endmacro %}
{% macro ifFalse(label, value) %}
{% if !value && value !== undefined %}
,{{ label }}: {{ value }}
{% endif %}
{% endmacro %}
{% macro ifNotUndefined(label, value) %}
{% if value !== undefined %}
,{{ label }}: {{ value }}
{% endif %}
{% endmacro %}
{% include "./table.html" %}
{% endautoescape %}
/**
* This file is auto generated by sequelize-pg-generator.
* @module path/to/model
* @author Özüm Eldoğan
*/
/*jslint node: true, stupid: true, nomen: true */
"use strict";
var Sequelize = require('sequelize'),
fs = require('fs'),
path = require('path'),
util = require('util'),
models = {},
relationships = {},
modelsPath = '',
definitionDir = 'definition-files',
definitionDirCustom = definitionDir + '-custom',
debug = false,
debugFD = '',
sequelize = null;
/**
* Requires given npm module file and defines sequelize module according to exported object from that module.
* @private
* @param {string} file - Location of the npm module file which contains model definition.
*/
function defineModel(file) {
var object = require(file),
options = object.options || {},
modelName = object.modelName;
if (debug) {
fs.writeSync(debugFD, 'var ' + modelName + ' = Sequelize.define("' + modelName + '",\n' + util.inspect(object.attributes) + ',\n' + util.inspect(options, {depth: null}) + ');\n\n\n');
}
models[modelName] = sequelize.define(modelName, object.attributes, options);
if (object.relations !== undefined) {
relationships[modelName] = object.relations;
}
}
/**
* Define 'hasMany' and 'belongsTo' relations.
* @private
* @param {string} modelName - Name of the model
* @param {string} relationType - Type of the relation 'hasMany' or 'belongsTo'
* @param {string} targetModelName - Name of the target model which this relation related to.
* @param {Object} options - Sequelize options of relation.
*/
function defineRelation(modelName, relationType, targetModelName, options) {
if (debug) {
fs.writeSync(debugFD, modelName + '.' + relationType + '(' + targetModelName + ', ' + util.inspect(options, {depth: null}) + ');\n\n');
}
models[modelName][relationType](models[targetModelName], options); // account.hasMany(contact, {...})
}
/**
* Generates list of definition files by looking given modelsPath directory. It traverses 'definition-files'
* and 'definition-files-custom' directories to generate the list. Files in 'definition-files' will be skipped
* if a file with same name is found in 'definition-files-custom' directory.
* @private
* @returns {Array}
* @example
* var list = getFileList('../model'); // ['./definition-files-custom/public_cart.js', './definition-files/public_account.js]
*/
function getFileList() {
var i, file, isOverridden = {}, files = [], customFiles, baseFiles;
baseFiles = fs.readdirSync(path.join(modelsPath, definitionDir));
customFiles = fs.readdirSync(path.join(modelsPath, definitionDirCustom));
for (i = 0; i < customFiles.length; i = i + 1) {
file = customFiles[i];
if (file.match(/\.js$/)) {
isOverridden[file] = true;
files.push('./' + path.join(definitionDirCustom, file));
}
}
for (i = 0; i < baseFiles.length; i = i + 1) {
file = baseFiles[i];
if (!isOverridden[file] && file.match(/\.js$/)) {
files.push('./' + path.join(definitionDir, file));
}
}
return files;
}
/**
* Iterates all relations and executes given callback on them. Callback is passed
* ({string} modelName, {string} relationType, {string} targetModelName, {Object} relationOptions)
* @private
* @param {function} callback - Callback function.
* @returns {Array}
*/
function processAllRelations(callback) {
var i, modelName, relation, relations, result = [];
for (modelName in relationships) {
if (relationships.hasOwnProperty(modelName)) {
relations = relationships[modelName];
for (i = 0; i < relations.length; i = i + 1) {
relation = relations[i];
result.push(callback(modelName, relation.type, relation.model, relation.details));
}
}
}
return result;
}
/**
* Initializes models.
* @private
*/
function init() {
var debugFile = path.join(__dirname, 'debug.js');
if (debug) {
if (fs.existsSync(debugFile)) { fs.unlinkSync(debugFile); }
debugFD = fs.openSync(debugFile, 'a');
}
getFileList(modelsPath).forEach(defineModel);
processAllRelations(defineRelation);
if (debug) {
fs.closeSync(debugFD);
}
}
module.exports = {};
/**
* Sets up sequelize models based on model files in given directory for given database details.
* @param {string} database - Name of the database to connect
* @param {string} username - Username of the database
* @param {string} password - Password of the database
* @param {Object} obj - Object to pass new Sequelize() function. See Sequelize for details.
* @example
* var orm = require('../model');
* orm.setup('path/to/model', 'database', 'user', 'password', {
* host: '127.0.0.1',
* logging: false,
* native: true
* });
*/
module.exports.setup = function (database, username, password, obj) {
if (typeof obj !== 'object') { obj = {}; }
if (obj.dialect === undefined || obj.dialect === null) { obj.dialect = 'postgres'; }
if (arguments.length === 2) {
sequelize = new Sequelize(database, username);
} else if (arguments.length === 3) {
sequelize = new Sequelize(database, username, password);
} else if (arguments.length === 4) {
sequelize = new Sequelize(database, username, password, obj);
}
modelsPath = __dirname;
init();
};
/**
* Returns requested model with given name.
* @param {string} name - Model name
* @returns {object} - Sequelize model
*/
module.exports.model = function (name) {
return models[name];
};
/**
* Returns Sequelize object.
* @returns {Sequelize} - Sequelize object
*/
module.exports.Sequelize = function () {
return Sequelize;
};
/**
* Returns sequelize instance.
* @returns {Sequelize} - sequelize instance
*/
module.exports.sequelize = function () {
return sequelize;
};
{% autoescape false %}
{
type: {{ relation.type }},
model: {{ relation.model }},
schema: {{ relation.targetSchema }},
table: {{ relation.targetTable }},
source: {{ relation.source }},
details: {
as: {{ relation.as }},
foreignKey: {{ relation.foreignKey }}
{{ ifTrue('otherKey', relation.otherKey) }}
{{ ifTrue('through', relation.through) }}
{{ ifTrue('onDelete', relation.onDelete) }}
{{ ifTrue('onUpdate', relation.onUpdate) }}
}
}
{% endautoescape %}
{% autoescape false %}
var orm = require('../index.js'),
{{ dataTypeVariable }} = orm.Sequelize();
module.exports = {
modelName: {{ table.modelName }},
options: {
tableName: {{ table.tableName }}
{{ ifTrue('schema', table.schema) }}
{{ ifTrue('omitNull', table.omitNull) }}
{{ ifFalse('timestamps', table.timestamps) }}
{{ ifTrue('paranoid', table.paranoid) }}
{{ ifTrue('underscored', table.underscored) }}
{{ ifTrue('underscoredAll', table.underscoredAll) }}
{{ ifTrue('freezeTableName', table.freezeTableName) }}
{{ ifTrue('createdAt', table.createdAt) }}
{{ ifTrue('updatedAt', table.updatedAt) }}
{{ ifTrue('deletedAt', table.deletedAt) }}
{{ ifTrue('charset', table.charset) }}
{{ ifTrue('collate', table.collate) }}
{{ ifTrue('comment', table.comment) }}
},
attributes: {
{% for column in table.columns %}
{% include "./column.html" %}{% if not loop.last %},{% endif %}
{% endfor %}
},
relations: [
{% for relation in table.relations %}
{% include "./relation.html" %}{% if not loop.last %},{% endif %}
{% endfor %}
]
};
{% endautoescape %}
\ No newline at end of file
{% autoescape false %}
{{ column.accessorName }}: {
type: {{ column.type }},
allowNull: {{ column.allowNull }},
xlabel: lang.t("{{"fields."+column.accessorName}}")
{{ ifTrue('field', column.name) }}
{{ ifTrue('primaryKey', column.primaryKey) }}
{{ ifTrue('autoIncrement', column.autoIncrement) }}
{{ ifFalse('allowNull', column.allowNull) }}
{{ ifNotUndefined('defaultValue', column.defaultValue) }}
{{ ifTrue('unique', column.unique) }}
{{ ifTrue('comment', column.comment) }}
{{ ifTrue('references', column.references) }}
{{ ifTrue('referencesKey', column.referencesKey) }}
{{ ifTrue('onUpdate', column.onUpdate) }}
{{ ifTrue('onDelete', column.onDelete) }}
}
{% endautoescape %}
{% autoescape false %}
/*------------------------------------------------------------------------------------
ARCHIVOS MODELOS GENERADOS AUTOMATICAMENTE, SE RECOMIENDA NO MODIFICAR LOS ARCHIVOS
Author: Felix Antonio Mamani Quispe
Email: felixddxd@gmail.com
La Paz - Bolivia
------------------------------------------------------------------------------------*/
"use strict";
const lang = require("../../lang");
const util = require("../../lib/util");
{% include "./table.html" %}
{% endautoescape %}
/**
* This file is auto generated by sequelize-pg-generator.
* @module path/to/model
* @author Özüm Eldoğan
*/
/*jslint node: true, stupid: true, nomen: true */
"use strict";
var Sequelize = require('sequelize'),
fs = require('fs'),
path = require('path'),
util = require('util'),
models = {},
relationships = {},
modelsPath = '',
definitionDir = 'definition-files',
definitionDirCustom = definitionDir + '-custom',
debug = false,
debugFD = '',
sequelize = null;
/**
* Requires given npm module file and defines sequelize module according to exported object from that module.
* @private
* @param {string} file - Location of the npm module file which contains model definition.
*/
function defineModel(file) {
var object = require(file),
options = object.options || {},
modelName = object.modelName;
if (debug) {
fs.writeSync(debugFD, 'var ' + modelName + ' = Sequelize.define("' + modelName + '",\n' + util.inspect(object.attributes) + ',\n' + util.inspect(options, {depth: null}) + ');\n\n\n');
}
models[modelName] = sequelize.define(modelName, object.attributes, options);
if (object.relations !== undefined) {
relationships[modelName] = object.relations;
}
}
/**
* Define 'hasMany' and 'belongsTo' relations.
* @private
* @param {string} modelName - Name of the model
* @param {string} relationType - Type of the relation 'hasMany' or 'belongsTo'
* @param {string} targetModelName - Name of the target model which this relation related to.
* @param {Object} options - Sequelize options of relation.
*/
function defineRelation(modelName, relationType, targetModelName, options) {
if (debug) {
fs.writeSync(debugFD, modelName + '.' + relationType + '(' + targetModelName + ', ' + util.inspect(options, {depth: null}) + ');\n\n');
}
models[modelName][relationType](models[targetModelName], options); // account.hasMany(contact, {...})
}
/**
* Generates list of definition files by looking given modelsPath directory. It traverses 'definition-files'
* and 'definition-files-custom' directories to generate the list. Files in 'definition-files' will be skipped
* if a file with same name is found in 'definition-files-custom' directory.
* @private
* @returns {Array}
* @example
* var list = getFileList('../model'); // ['./definition-files-custom/public_cart.js', './definition-files/public_account.js]
*/
function getFileList() {
var i, file, isOverridden = {}, files = [], customFiles, baseFiles;
baseFiles = fs.readdirSync(path.join(modelsPath, definitionDir));
customFiles = fs.readdirSync(path.join(modelsPath, definitionDirCustom));
for (i = 0; i < customFiles.length; i = i + 1) {
file = customFiles[i];
if (file.match(/\.js$/)) {
isOverridden[file] = true;
files.push('./' + path.join(definitionDirCustom, file));
}
}
for (i = 0; i < baseFiles.length; i = i + 1) {
file = baseFiles[i];
if (!isOverridden[file] && file.match(/\.js$/)) {
files.push('./' + path.join(definitionDir, file));
}
}
return files;
}
/**
* Iterates all relations and executes given callback on them. Callback is passed
* ({string} modelName, {string} relationType, {string} targetModelName, {Object} relationOptions)
* @private
* @param {function} callback - Callback function.
* @returns {Array}
*/
function processAllRelations(callback) {
var i, modelName, relation, relations, result = [];
for (modelName in relationships) {
if (relationships.hasOwnProperty(modelName)) {
relations = relationships[modelName];
for (i = 0; i < relations.length; i = i + 1) {
relation = relations[i];
result.push(callback(modelName, relation.type, relation.model, relation.details));
}
}
}
return result;
}
/**
* Initializes models.
* @private
*/
function init() {
var debugFile = path.join(__dirname, 'debug.js');
if (debug) {
if (fs.existsSync(debugFile)) { fs.unlinkSync(debugFile); }
debugFD = fs.openSync(debugFile, 'a');
}
getFileList(modelsPath).forEach(defineModel);
processAllRelations(defineRelation);
if (debug) {
fs.closeSync(debugFD);
}
}
module.exports = {};
/**
* Sets up sequelize models based on model files in given directory for given database details.
* @param {string} database - Name of the database to connect
* @param {string} username - Username of the database
* @param {string} password - Password of the database
* @param {Object} obj - Object to pass new Sequelize() function. See Sequelize for details.
* @example
* var orm = require('../model');
* orm.setup('path/to/model', 'database', 'user', 'password', {
* host: '127.0.0.1',
* logging: false,
* native: true
* });
*/
module.exports.setup = function (database, username, password, obj) {
if (typeof obj !== 'object') { obj = {}; }
if (obj.dialect === undefined || obj.dialect === null) { obj.dialect = 'postgres'; }
if (arguments.length === 2) {
sequelize = new Sequelize(database, username);
} else if (arguments.length === 3) {
sequelize = new Sequelize(database, username, password);
} else if (arguments.length === 4) {
sequelize = new Sequelize(database, username, password, obj);
}
modelsPath = __dirname;
init();
};
/**
* Returns requested model with given name.
* @param {string} name - Model name
* @returns {object} - Sequelize model
*/
module.exports.model = function (name) {
return models[name];
};
/**
* Returns Sequelize object.
* @returns {Sequelize} - Sequelize object
*/
module.exports.Sequelize = function () {
return Sequelize;
};
/**
* Returns sequelize instance.
* @returns {Sequelize} - sequelize instance
*/
module.exports.sequelize = function () {
return sequelize;
};
{% autoescape false %}
{
type: {{ relation.type }},
model: {{ relation.model }},
schema: {{ relation.targetSchema }},
table: {{ relation.targetTable }},
source: {{ relation.source }},
details: {
as: {{ relation.as }},
foreignKey: {{ relation.foreignKey }}
{{ ifTrue('otherKey', relation.otherKey) }}
{{ ifTrue('through', relation.through) }}
{{ ifTrue('onDelete', relation.onDelete) }}
{{ ifTrue('onUpdate', relation.onUpdate) }}
}
}
{% endautoescape %}
{% autoescape false %}
module.exports = (sequelize, DataTypes) => {
let fields = {
{% for column in table.columns %}
{% include "./column.html" %}{% if not loop.last %},{% endif %}
{% endfor %}
}
fields = util.setTimestamps(fields);
let {{table.modelName}}= sequelize.define("{{ table.tableName }}", fields, {
timestamps: false,
tableName: "{{ table.tableName }}",
schema: "{{ table.schema }}",
});
return {{table.modelName}};
};
{% endautoescape %}
\ No newline at end of file
{% autoescape false %}
{{ column.accessorName }}: {
type: {{ column.type }}
{{ ifTrue('field', column.name) }}
{{ ifTrue('primaryKey', column.primaryKey) }}
{{ ifTrue('autoIncrement', column.autoIncrement) }}
{{ ifFalse('allowNull', column.allowNull) }}
{{ ifNotUndefined('defaultValue', column.defaultValue) }}
{{ ifTrue('unique', column.unique) }}
{{ ifTrue('comment', column.comment) }}
{% if column.references && column.referencesKey %}
,references: { model: {{column.references}}, key: {{column.referencesKey}} }
{% endif %}
{{ ifTrue('onUpdate', column.onUpdate) }}
{{ ifTrue('onDelete', column.onDelete) }}
}
{% endautoescape %}
{% autoescape false %}
/*jslint node: true */
"use strict";
{%- if warning %}
/*------------------------------------------------------------------------------------
DO NOT EDIT THIS FILE !!! It is generated automatically and will be overwritten.
To modify this model:
1. Create '{{ table.baseFileName }}.js' file in 'definition-files-custom' directory located in this file's parent directory.
2. Copy the code below and paste it into '{{ table.baseFileName }}.js'.
3. Use utility methods to easily access orm properties.
"use strict";
var orm = require('{{mainScript}}'),
model = require('./{{ table.baseFileName }}.js'),
util = require('../utils.js')(model),
Seq = orm.Sequelize();
module.exports = model;
// Some utility methods:
{% if table.relations|first %}util.getRelation({{ table.relations|first.as }}).onDelete = 'CASCADE'; {% endif %}
{% if table.columns|first %}util.getAttribute({{table.columns|first.accessorName}}).comment = 'This is the comment'; {% endif %}
------------------------------------------------------------------------------------*/
{%- endif %}
{% macro ifTrue(label, value) %}
{% if value %}
,{{ label }}: {{ value }}
{% endif %}
{% endmacro %}
{% macro ifFalse(label, value) %}
{% if !value && value !== undefined %}
,{{ label }}: {{ value }}
{% endif %}
{% endmacro %}
{% macro ifNotUndefined(label, value) %}
{% if value !== undefined %}
,{{ label }}: {{ value }}
{% endif %}
{% endmacro %}
{% include "./table.html" %}
{% endautoescape %}
/**
* This file is auto generated by sequelize-pg-generator.
* @module path/to/model
* @author Özüm Eldoğan
*/
/*jslint node: true, stupid: true, nomen: true */
"use strict";
var Sequelize = require('sequelize'),
fs = require('fs'),
path = require('path'),
util = require('util'),
models = {},
relationships = {},
modelsPath = '',
definitionDir = 'definition-files',
definitionDirCustom = definitionDir + '-custom',
debug = false,
debugFD = '',
sequelize = null;
/**
* Requires given npm module file and defines sequelize module according to exported object from that module.
* @private
* @param {string} file - Location of the npm module file which contains model definition.
*/
function defineModel(file) {
var object = require(file),
options = object.options || {},
modelName = object.modelName;
if (debug) {
fs.writeSync(debugFD, 'var ' + modelName + ' = Sequelize.define("' + modelName + '",\n' + util.inspect(object.attributes) + ',\n' + util.inspect(options, {depth: null}) + ');\n\n\n');
}
models[modelName] = sequelize.define(modelName, object.attributes, options);
if (object.relations !== undefined) {
relationships[modelName] = object.relations;
}
}
/**
* Define 'hasMany' and 'belongsTo' relations.
* @private
* @param {string} modelName - Name of the model
* @param {string} relationType - Type of the relation 'hasMany' or 'belongsTo'
* @param {string} targetModelName - Name of the target model which this relation related to.
* @param {Object} options - Sequelize options of relation.
*/
function defineRelation(modelName, relationType, targetModelName, options) {
if (debug) {
fs.writeSync(debugFD, modelName + '.' + relationType + '(' + targetModelName + ', ' + util.inspect(options, {depth: null}) + ');\n\n');
}
models[modelName][relationType](models[targetModelName], options); // account.hasMany(contact, {...})
}
/**
* Generates list of definition files by looking given modelsPath directory. It traverses 'definition-files'
* and 'definition-files-custom' directories to generate the list. Files in 'definition-files' will be skipped
* if a file with same name is found in 'definition-files-custom' directory.
* @private
* @returns {Array}
* @example
* var list = getFileList('../model'); // ['./definition-files-custom/public_cart.js', './definition-files/public_account.js]
*/
function getFileList() {
var i, file, isOverridden = {}, files = [], customFiles, baseFiles;
baseFiles = fs.readdirSync(path.join(modelsPath, definitionDir));
customFiles = fs.readdirSync(path.join(modelsPath, definitionDirCustom));
for (i = 0; i < customFiles.length; i = i + 1) {
file = customFiles[i];
if (file.match(/\.js$/)) {
isOverridden[file] = true;
files.push('./' + path.join(definitionDirCustom, file));
}
}
for (i = 0; i < baseFiles.length; i = i + 1) {
file = baseFiles[i];
if (!isOverridden[file] && file.match(/\.js$/)) {
files.push('./' + path.join(definitionDir, file));
}
}
return files;
}
/**
* Iterates all relations and executes given callback on them. Callback is passed
* ({string} modelName, {string} relationType, {string} targetModelName, {Object} relationOptions)
* @private
* @param {function} callback - Callback function.
* @returns {Array}
*/
function processAllRelations(callback) {
var i, modelName, relation, relations, result = [];
for (modelName in relationships) {
if (relationships.hasOwnProperty(modelName)) {
relations = relationships[modelName];
for (i = 0; i < relations.length; i = i + 1) {
relation = relations[i];
result.push(callback(modelName, relation.type, relation.model, relation.details));
}
}
}
return result;
}
/**
* Initializes models.
* @private
*/
function init() {
var debugFile = path.join(__dirname, 'debug.js');
if (debug) {
if (fs.existsSync(debugFile)) { fs.unlinkSync(debugFile); }
debugFD = fs.openSync(debugFile, 'a');
}
getFileList(modelsPath).forEach(defineModel);
processAllRelations(defineRelation);
if (debug) {
fs.closeSync(debugFD);
}
}
module.exports = {};
/**
* Sets up sequelize models based on model files in given directory for given database details.
* @param {string} database - Name of the database to connect
* @param {string} username - Username of the database
* @param {string} password - Password of the database
* @param {Object} obj - Object to pass new Sequelize() function. See Sequelize for details.
* @example
* var orm = require('../model');
* orm.setup('path/to/model', 'database', 'user', 'password', {
* host: '127.0.0.1',
* logging: false,
* native: true
* });
*/
module.exports.setup = function (database, username, password, obj) {
if (typeof obj !== 'object') { obj = {}; }
if (obj.dialect === undefined || obj.dialect === null) { obj.dialect = 'postgres'; }
if (arguments.length === 2) {
sequelize = new Sequelize(database, username);
} else if (arguments.length === 3) {
sequelize = new Sequelize(database, username, password);
} else if (arguments.length === 4) {
sequelize = new Sequelize(database, username, password, obj);
}
modelsPath = __dirname;
init();
};
/**
* Returns requested model with given name.
* @param {string} name - Model name
* @returns {object} - Sequelize model
*/
module.exports.model = function (name) {
return models[name];
};
/**
* Returns Sequelize object.
* @returns {Sequelize} - Sequelize object
*/
module.exports.Sequelize = function () {
return Sequelize;
};
/**
* Returns sequelize instance.
* @returns {Sequelize} - sequelize instance
*/
module.exports.sequelize = function () {
return sequelize;
};
{% autoescape false %}
{
type: {{ relation.type }},
model: {{ relation.model }},
schema: {{ relation.targetSchema }},
table: {{ relation.targetTable }},
source: {{ relation.source }},
details: {
as: {{ relation.as }},
foreignKey: {{ relation.foreignKey }}
{{ ifTrue('otherKey', relation.otherKey) }}
{{ ifTrue('through', relation.through) }}
{{ ifTrue('onDelete', relation.onDelete) }}
{{ ifTrue('onUpdate', relation.onUpdate) }}
}
}
{% endautoescape %}
{% autoescape false %}
var orm = require('../index.js'),
{{ dataTypeVariable }} = orm.Sequelize();
module.exports = {
modelName: {{ table.modelName }},
options: {
tableName: {{ table.tableName }}
{{ ifTrue('schema', table.schema) }}
{{ ifTrue('omitNull', table.omitNull) }}
{{ ifFalse('timestamps', table.timestamps) }}
{{ ifTrue('paranoid', table.paranoid) }}
{{ ifTrue('underscored', table.underscored) }}
{{ ifTrue('underscoredAll', table.underscoredAll) }}
{{ ifTrue('freezeTableName', table.freezeTableName) }}
{{ ifTrue('createdAt', table.createdAt) }}
{{ ifTrue('updatedAt', table.updatedAt) }}
{{ ifTrue('deletedAt', table.deletedAt) }}
{{ ifTrue('charset', table.charset) }}
{{ ifTrue('collate', table.collate) }}
{{ ifTrue('comment', table.comment) }}
},
attributes: {
{% for column in table.columns %}
{% include "./column.html" %}{% if not loop.last %},{% endif %}
{% endfor %}
},
relations: [
{% for relation in table.relations %}
{% include "./relation.html" %}{% if not loop.last %},{% endif %}
{% endfor %}
]
};
{% endautoescape %}
\ No newline at end of file
/**
* Utility methods to modify and customize auto generated models without affecting further auto generations.
* Require this module from model customization scripts located in path/to/model/definitions-files-custom directory.
* @class
* @author Özüm Eldoğan
*/
/*jslint node: true */
"use strict";
/**
* @constructor
* @param model
*/
var GeneratorUtil = function (model) {
this.model = model;
};
/**
* Searches and returns relation with the given alias. Alias is defined in sequelize options with parameter 'as'
* @method
* @param {string} as - Alias of the relation.
* @returns {Object}
*/
GeneratorUtil.prototype.getRelation = function (as) {
var i,
relations = this.model.relations;
for (i = 0; i < relations.length; i = i + 1) {
if (relations[i].details.as === as) {
return relations[i];
}
}
};
/**
* Searches and returns attribute with the given alias. Alias is defined in sequelize options with parameter 'as'
* @method
* @param {string} name - Name of the attribute.
* @returns {Object}
*/
GeneratorUtil.prototype.getAttribute = function (name) {
return this.model.attributes[name];
};
/**
* Searches and returns attribute with the given alias. Alias is defined in sequelize options with parameter 'as'
* @method
* @param {string} oldName - Name of the attribute which it's name to be changed.
* @param {string} newName - New name of the attribute.
* @throws Will throw error if there is already an attribute with new name exists or attribute with oldName does not exists.
*/
GeneratorUtil.prototype.renameAttribute = function (oldName, newName) {
if (this.model.attributes[newName] !== undefined) {
throw new Error('There is already an attribute with the same name ("' + newName + '") in table "' + this.model.modelName + '".');
}
if (this.model.attributes[oldName] === undefined) {
throw new Error('There is no attribute with the name "' + oldName + '". in table "' + this.model.modelName + '".');
}
this.model.attributes[newName] = this.model.attributes[oldName];
delete this.model.attributes[oldName];
};
/**
* Creates and returns new object with utility functions.
* @param model
* @returns {GeneratorUtil}
*/
module.exports = function (model) {
return new GeneratorUtil(model);
};
/*jslint node: true, stupid: true, nomen:true */
/*global describe, it, before, beforeEach, after, afterEach */
"use strict";
var assert = require('chai').assert;
var testDB = require('./util/db.js');
var path = require('path');
var fs = require('fs-extra');
var cart, account;
before(function (done) {
testDB.generate(1, { resetConfig: true, nolog: true, config: path.join(__dirname, 'util', 'config', 'reverse-config.json'), output: path.join(__dirname, 'model-different') }, done);
});
before(function(done) {
cart = require('./model-different/definition-files/cart.js');
account = require('./model-different/definition-files/account.js');
done();
});
after(function (done) {
fs.removeSync(path.join(__dirname, 'model-different'));
testDB.dropDB(done);
});
describe('cart', function () {
it('should have model file.', function () {
assert.isTrue(fs.existsSync(path.join(__dirname, 'model-different', 'definition-files', 'cart.js')));
});
it('should have model name.', function () {
assert.equal(cart.modelName, 'cart');
});
it('should have createdAt attribute.', function () {
assert.equal(cart.attributes.created_at.field, 'created_at');
});
it('should have relations.', function () {
assert.equal(cart.relations.length, 3);
});
});
describe('account', function () {
it('should not have relation to other_schema.', function () {
var found = false;
account.relations.forEach(function (relation) {
if (relation.model === 'otherSchema.otherSchemaTable') {
found = true;
}
assert.isFalse(found);
});
});
it('should have true as default value for is_active', function() {
assert.equal(account.attributes.is_active.defaultValue, true);
});
it('should have false as default value for def_false', function() {
assert.equal(account.attributes.def_false.defaultValue, false);
});
});
/*jslint node: true, stupid: true, nomen:true */
/*global describe, it, before, beforeEach, after, afterEach */
"use strict";
var assert = require('chai').assert;
var testDB = require('./util/db.js');
var path = require('path');
var fs = require('fs-extra');
var cart, account;
before(function (done) {
testDB.generate(1, { resetConfig: true, nolog: true, config: path.join(__dirname, 'util', 'config', 'template-sequelize4.json'), output: path.join(__dirname, 'model-sequelize4') }, done);
});
before(function(done) {
cart = require('./model-sequelize4/definition-files/public_cart.js');
account = require('./model-sequelize4/definition-files/public_account.js');
done();
});
after(function (done) {
fs.removeSync(path.join(__dirname, 'model-sequelize4'));
testDB.dropDB(done);
});
describe('cart', function () {
it('should have model file.', function () {
assert.isTrue(fs.existsSync(path.join(__dirname, 'model-sequelize4', 'definition-files', 'public_cart.js')));
});
it('should have references object.', function () {
assert.deepEqual(cart.attributes.contactId.references, {
model: "public.contact",
key: "contact_id"
});
});
});
/*jslint node: true, stupid: true, nomen:true */
/*global describe, it, before, beforeEach, after, afterEach */
"use strict";
var assert = require('chai').assert;
var testDB = require('./util/db.js');
var path = require('path');
var fs = require('fs-extra');
var cart, account;
before(function (done) {
testDB.generate(1, { resetConfig: true, nolog: true, output: path.join(__dirname, 'model') }, done);
});
before(function(done) {
cart = require('./model/definition-files/public_cart.js');
account = require('./model/definition-files/public_account.js');
done();
});
after(function (done) {
fs.removeSync(path.join(__dirname, 'model'));
testDB.dropDB(done);
});
describe('public.cart', function () {
it('should have model file.', function () {
assert.isTrue(fs.existsSync(path.join(__dirname, 'model', 'definition-files', 'public_cart.js')));
});
it('should have model name.', function () {
assert.equal(cart.modelName, 'public.cart');
});
it('should have createdAt attribute.', function () {
assert.equal(cart.attributes.createdAt.field, 'created_at');
});
it('should have relations.', function () {
assert.equal(cart.relations.length, 3);
});
});
describe('public.account', function () {
it('should have relation to other_schema.', function () {
var found = false;
account.relations.forEach(function (relation) {
if (relation.model === 'otherSchema.otherSchemaTable') {
found = true;
}
assert.isTrue(found);
});
});
});
\ No newline at end of file
/*jslint node: true, stupid: true, nomen:true */
/*global describe, it, before, beforeEach, after, afterEach */
"use strict";
var assert = require('chai').assert;
var testDB = require('./util/db.js');
var path = require('path');
var fs = require('fs-extra');
var account, contact;
before(function (done) {
testDB.generate(1, { resetConfig: true, nolog: true, output: path.join(__dirname, 'model') }, done);
});
before(function(done) {
var orm = require('./model');
orm.setup(testDB.dbConfig.database, testDB.dbConfig.user, testDB.dbConfig.password, { host: testDB.dbConfig.host, logging: false});
var sequelize = orm.sequelize;
account = orm.model('public.account'); // Can be configured without schema.
contact = orm.model('public.contact'); // Can be configured without schema.
done();
});
after(function (done) {
fs.removeSync(path.join(__dirname, 'model'));
testDB.dropDB(done);
});
describe('public.account', function () {
// Test one-to-many
it('should have many primary contacts.', function (done) {
account.findAll({ include: [ { model: contact, as: "primaryContacts" } ] }).then(function(data) {
assert.equal(data[0].primaryContacts[0].name, "Özüm");
done();
});
});
});
\ No newline at end of file
{
"sequelize-pg-generator": {
"database": {
"schema": ["public"]
},
"generate": {
"stripFirstTableFromHasMany": false,
"addTableNameToManyToMany": false,
"hasManyThrough": false,
"belongsToMany": true,
"prefixForBelongsTo": "custom",
"useSchemaName": false,
"modelCamelCase": false,
"relationAccessorCamelCase": false,
"columnAccessorCamelCase": false,
"columnDefault": true,
"columnDescription": false,
"columnAutoIncrement": false,
"tableDescription": false,
"dataTypeVariable": "Sequelize",
"skipTable": ["type_table"]
}
}
}
\ No newline at end of file
{
"sequelize-pg-generator": {
"template": {
"folder": "template/sequelize4"
}
}
}
\ No newline at end of file
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
/*jslint node: true, nomen: true, stupid: true */
"use strict";
var fs = require('fs');
var path = require('path');
var pg = require('pg');
var async = require('async');
var lodash = require('lodash');
var dbConfig = { host: 'localhost', port: 5432, user: 'user', password: 'password', database: 'pg_generator_test_625393' };
var generator = require('../../lib/index.js');
var conString = 'postgres://' + dbConfig.user + ':' + dbConfig.password + '@' + dbConfig.host + ':' + dbConfig.port + '/'; //'postgres://user:pass@host:port/'
var conStringTest = conString + dbConfig.database; //'postgres://user:pass@host:port/db'
var conStringTemplate = conString + 'template1'; //'postgres://user:pass@host:port/db'
var sql = {
createDB : "CREATE DATABASE pg_generator_test_625393 WITH ENCODING = 'UTF8' TEMPLATE = template0;",
dropDB : "DROP DATABASE IF EXISTS pg_generator_test_625393;",
createSchema : function (sqlID) { return fs.readFileSync(path.join(__dirname, 'create-test-db-' + sqlID + '.sql')).toString(); },
dropConnection : "SELECT pg_terminate_backend(pid) FROM pg_stat_activity where datname='pg_generator_test_625393';"
};
pg.on('error', function (err) {
// Do nothing on termination due to admin command. We do this to drop previously created test db.
if (!err.message.match('terminating connection due to administrator command')) { console.log('Database error!', err); }
});
module.exports.dbConfig = dbConfig;
module.exports.generate = function generate(sqlId, options, callback) {
module.exports.resetDB(sqlId, function () {
generator(function (err) {
if (err) { callback(err); return; }
callback();
}, lodash.defaults(options, {
database: 'pg_generator_test_625393',
user: dbConfig.user,
password: dbConfig.password,
output: path.join(__dirname, '..', 'model'),
schema: ['public', 'other_schema'],
nolog: true
}));
});
};
module.exports.resetDB = function resetDB(sqlID, callback) {
if (sqlID === undefined) { sqlID = 1; }
var client = new pg.Client(conStringTemplate);
client.connect(function () {
async.series([
client.query.bind(client, sql.dropConnection),
client.query.bind(client, sql.dropDB),
client.query.bind(client, sql.createDB),
function (next) {
var clientTest = new pg.Client(conStringTest);
clientTest.connect(function () {
clientTest.query(sql.createSchema(sqlID), function () {
clientTest.end();
next();
});
});
}
], function (err) {
if (err) { throw err; }
client.end();
callback();
});
});
};
module.exports.dropDB = function dropDB(callback) {
var client = new pg.Client(conStringTemplate);
client.connect(function () {
async.series([
client.query.bind(client, sql.dropConnection),
client.query.bind(client, sql.dropDB)
], function (err) {
if (err) { throw err; }
client.end();
callback();
});
});
};
module.exports.dbConfig = dbConfig;
\ No newline at end of file