masterrecord 0.0.31 → 0.0.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,7 +17,7 @@
17
17
 
18
18
  */
19
19
 
20
- // version 1.0.16
20
+ // version 0.0.2
21
21
  class EntityModel {
22
22
 
23
23
  constructor(name){
@@ -1,4 +1,4 @@
1
- var modelDB = require('./EntityModel');
1
+ var modelDB = require('./entityModel');
2
2
 
3
3
  // creates new instance if entity model and calls inner functions to build out a valid entity
4
4
  class EntityModelBuilder {
package/Masterrecord.js CHANGED
@@ -14,7 +14,7 @@ class masterrecord{
14
14
  }
15
15
 
16
16
 
17
- module.exports = masterrecord;
17
+ module.exports = new masterrecord();
18
18
 
19
19
 
20
20
 
package/Migrations/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // version 0.0.4
3
+ // version 0.0.5
4
4
  // https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/migrations/
5
5
  // how to add environment variables on cli call example - master=development masterrecord add-migration auth authContext
6
6
 
@@ -16,10 +16,10 @@ const [,, ...args] = process.argv
16
16
 
17
17
  program
18
18
  .version('0.0.2')
19
- .option('-v, --version', '0.0.31')
19
+ .option('-v, --version', '0.0.33')
20
20
  .description('A ORM framework that facilitates the creation and use of business objects whose data requires persistent storage to a database');
21
21
 
22
- // Instructions : to run command you must go to main project folder is located and run the command using the context file name.
22
+ // Instructions : to run command you must go to main project folder is located and run the command using the context file name.
23
23
  program
24
24
  .command('enable-migrations <contextFileName>')
25
25
  .alias('em')
@@ -30,12 +30,13 @@ program
30
30
  // location of folder where command is being executed..
31
31
  var executedLocation = process.cwd();
32
32
  // find context file from main folder location
33
- var contextInstance = migration.getContext(executedLocation, contextFileName);
34
-
33
+ var contextInstance = migration.findContext(executedLocation, contextFileName);
34
+ var context = new contextInstance.context();
35
35
  var snap = {
36
36
  file : contextInstance.fileLocation,
37
37
  executedLocation : executedLocation,
38
- context : new contextInstance.context(),
38
+ context : context,
39
+ contextEntities : [],
39
40
  contextFileName: contextFileName.toLowerCase()
40
41
  }
41
42
 
@@ -54,30 +55,33 @@ program
54
55
  var migration = new Migration();
55
56
  try{
56
57
  // find context file from main folder location
57
- var search = `${executedLocation}/**/*${contextFileName}_contextSnapShot.json`;
58
-
59
- var files = globSearch.sync(search, executedLocation);
60
- var contextSnapshot = require(files[0]);
61
- var context = require(contextSnapshot.contextLocation);
62
- var contextInstance = new context();
63
- var newEntity = migration.buildMigrationTemplate(name, contextSnapshot.schema, contextInstance .__entities);
64
- var migrationDate = Date.now();
65
- var file = `${contextSnapshot.migrationFolder}/${migrationDate}_${name}_migration.js`
66
- fs.writeFile(file, newEntity, 'utf8', function (err) {
67
- if (err) return console.log("--- Error running cammand, rlease run command add-migration ---- ", err);
68
-
69
- });
58
+ var search = `${executedLocation}/**/*${contextFileName}_contextSnapShot.json`;
59
+ var files = globSearch.sync(search, executedLocation);
60
+ var file = files[0];
61
+ if(file){
62
+ var contextSnapshot = require(files[0]);
63
+ var context = require(contextSnapshot.contextLocation);
64
+ var contextInstance = new context();
65
+ var newEntity = migration.template(name, contextSnapshot.schema, contextInstance .__entities);
66
+ var migrationDate = Date.now();
67
+ var file = `${contextSnapshot.migrationFolder}/${migrationDate}_${name}_migration.js`
68
+ fs.writeFile(file, newEntity, 'utf8', function (err) {
69
+ if (err) return console.log("--- Error running cammand, rlease run command add-migration ---- ", err);
70
+ });
71
+ console.log(`${name} migration file created`);
72
+ }
73
+ else{
74
+ console.log("Error - Cannot read or find Context file");
75
+ }
70
76
  }catch (e){
71
- console.log("Cannot read or find file ", e);
77
+ console.log("Error - Cannot read or find file ", e);
72
78
  }
73
-
74
- console.log(`${name} migration file created`);
75
79
  });
76
80
 
77
81
  program
78
82
  .command('update-database <contextFileName>')
79
83
  .alias('ud')
80
- .description('Apply pending migrations to database')
84
+ .description('Apply pending migrations to database - up method call')
81
85
  .action(function(contextFileName){
82
86
  var executedLocation = process.cwd();
83
87
  contextFileName = contextFileName.toLowerCase();
@@ -87,54 +91,84 @@ program
87
91
  var search = `${executedLocation}/**/*${contextFileName}_contextSnapShot.json`;
88
92
  var files = globSearch.sync(search, executedLocation);
89
93
  var file = files[0];
90
- var contextSnapshot = require(file);
91
-
92
- var searchMigration = `${contextSnapshot.migrationFolder}/**/*_migration.js`;
93
- var migrationFiles = globSearch.sync(searchMigration, contextSnapshot.migrationFolder);
94
- if( migrationFiles){
95
- // find newest migration file
96
- var mFiles = migrationFiles.sort(function(x, y){
97
- return new Date(x.timestamp) < new Date(y.timestamp) ? 1 : -1
98
- });
99
-
100
- var mFile = mFiles[0];
101
- console.log("ontextSnapshot -------------",mFile);
102
- var migrationFile = require(mFile);
103
- var context = require(contextSnapshot.contextLocation);
104
- var contextInstance = new context();
105
-
106
- var newMigrationInstance = new migrationFile(context);
107
-
108
- var tableList = migration.callMigrationUp(contextSnapshot.schema, contextInstance.__entities);
109
- //newMigrationInstance.up(tableList);
94
+ if(file){
95
+ var contextSnapshot = require(file);
96
+ var searchMigration = `${contextSnapshot.migrationFolder}/**/*_migration.js`;
97
+ var migrationFiles = globSearch.sync(searchMigration, contextSnapshot.migrationFolder);
98
+ if( migrationFiles){
99
+
100
+ // find newest migration file
101
+ var mFiles = migrationFiles.sort(function(x, y){
102
+ return new Date(x.timestamp) < new Date(y.timestamp) ? 1 : -1
103
+ });
104
+
105
+ var mFile = mFiles[0];
106
+ var migrationFile = require(mFile);
107
+ var context = require(contextSnapshot.contextLocation);
108
+ var contextInstance = new context();
109
+ var newMigrationInstance = new migrationFile(context);
110
+
111
+ var tableObj = migration.up(contextSnapshot.schema, contextInstance.__entities);
112
+ newMigrationInstance.up(tableObj);
113
+
114
+ var snap = {
115
+ file : contextSnapshot.contextLocation,
116
+ executedLocation : executedLocation,
117
+ context : contextInstance,
118
+ contextEntities : contextInstance.__entities,
119
+ contextFileName: contextFileName
120
+ }
121
+
122
+ migration.createSnapShot(snap);
123
+ console.log("database updated");
124
+ }
125
+ else{
126
+ console.log("Error - Cannot read or find migration file");
127
+ }
128
+
110
129
  }
130
+ else{
131
+ console.log("Error - Cannot read or find Context file");
132
+ }
111
133
  }catch (e){
112
- console.log("Cannot read or find file ", e);
134
+ console.log("Error - Cannot read or find file ", e);
113
135
  }
114
- console.log("databasedsdsd updated");
115
136
  });
116
137
 
117
- // we will find the migration folder inside the nearest app folder if no migration folder is location is added
118
- program
119
- .command('remove-migration <name> <migrationFolderLocation>')
120
- .alias('rm')
121
- .description('Removes the last migration that has not been applied')
122
- .action(function(name){
123
- // remove migrations call the down method of a migration newMigrationInstance.down();
124
- // find migration file using name and delete it.
125
- });
126
138
 
139
+ program
140
+ .command('get-migrations <contextFileName>')
141
+ .alias('gm')
142
+ .description('Get a list of migration file names using the context')
143
+ .action(function(contextFileName){
144
+ var executedLocation = process.cwd();
145
+ contextFileName = contextFileName.toLowerCase();
146
+ var search = `${executedLocation}/**/*${contextFileName}_contextSnapShot.json`;
147
+ var files = globSearch.sync(search, executedLocation);
148
+ var file = files[0];
149
+ if(file){
150
+ var contextSnapshot = require(file);
151
+ var searchMigration = `${contextSnapshot.migrationFolder}/**/*_migration.js`;
152
+ var migrationFiles = globSearch.sync(searchMigration, contextSnapshot.migrationFolder);
153
+ if( migrationFiles){
154
+ console.log("MIgration File List", migrationFiles);
155
+ return migrationFiles;
156
+ }
157
+ }
158
+ else{
159
+ console.log("Error - Cannot read or find Context file");
160
+ }
161
+ });
127
162
 
128
- // we will find the migration folder inside the nearest app folder if no migration folder is location is added
163
+ // we will find the migration folder inside the nearest app folder if no migration folder is location is added
129
164
  program
130
- .command('revert-migration <name> <migrationFolderLocation>')
131
- .alias('rm')
132
- .description('Reverts back to the last migration with given name')
133
- .action(function(cmd){
134
- var dir = process.cwd();
135
- console.log("starting server");
136
- require(dir + '/server.js');
137
- //return "node c:\node\server.js"
165
+ .command('update-database-target <migrationFileName>')
166
+ .alias('udt')
167
+ .description('Apply pending migrations to database - down method call')
168
+ .action(function(migrationFileName){
169
+ // this will call all the down methods until it gets to the one your looking for. First it needs to validate that there is such a file.
138
170
  });
139
171
 
172
+
173
+
140
174
  program.parse(process.argv);
@@ -1,11 +1,82 @@
1
1
 
2
-
2
+ // verison 0.0.3
3
3
  class migrationSQLiteQuery {
4
4
 
5
+ #tempTableName = "_temp_alter_column_update"
6
+
7
+ #getTableColumns(table){
8
+ var columnList = [];
9
+ for (var key in table) {
10
+ if(typeof table[key] === "object"){
11
+ columnList.push(table[key].name);
12
+ }
13
+ }
14
+ return columnList.join(',');;
15
+ }
16
+
17
+ #columnMapping(table){
18
+ /*
19
+ var mapping = {
20
+ "name": "id", // if this chnages then call rename column
21
+ "type": "integer", // if this changes then call altercolumn
22
+ "primary": false, // is primary key
23
+ "nullable": false, // is nullable
24
+ "unique": true, // vlaue has to be uniqe
25
+ "auto": true, // sets the value to AUTOINCREMENT
26
+ "cascadeOnDelete": true,
27
+ "lazyLoading": true,
28
+ "isNavigational": false
29
+
30
+ }
31
+ */
32
+ // name TEXT NOT NULL,
33
+
34
+ var auto = table.auto ? " AUTOINCREMENT":"";
35
+ var primaryKey = table.primary ? " PRIMARY KEY" : "";
36
+ var nullName = table.nullable ? "" : " NOT NULL";
37
+ var unique = table.unique ? " UNIQUE" : "";
38
+ var type = this.#typeManager(table.type);
39
+
40
+ return `${table.name} ${type}${nullName}${unique}${primaryKey}${auto}`;
41
+ }
42
+
43
+ #typeManager(type){
44
+ switch(type) {
45
+ case "string":
46
+ return "TEXT"
47
+ break;
48
+ case "time":
49
+ return "TEXT"
50
+ break;
51
+ case "boolean":
52
+ return "INTEGER"
53
+ break;
54
+ case "integer":
55
+ return "INTEGER"
56
+ break;
57
+ }
58
+
59
+ }
60
+
61
+ alterColumn(fullTable, table){
62
+ if(table){
63
+ table.newName = this.tempTableName;
64
+ return {
65
+ 1 : this.renameTable(table),
66
+ 2 : this.createTable(table.tableName, fullTable),
67
+ 3 : this.insertInto(table.tableName, fullTable),
68
+ 4 : this.dropTable(this.tempTableName)
69
+ }
70
+ }
71
+ else{
72
+ console.log("table information is null")
73
+ }
74
+ }
75
+
76
+
5
77
  addColum(table){
6
- var buildDefinations = this.buildDefinations(table);
7
- return `ALTER TABLE ${table.name}
8
- ADD ${table.column} ${buildDefinations}`;
78
+ return `ALTER TABLE ${table.tableName}
79
+ ADD COLUMN ${table.name}`;
9
80
 
10
81
  /*
11
82
  column definations
@@ -17,16 +88,30 @@ class migrationSQLiteQuery {
17
88
  */
18
89
  }
19
90
 
20
- buildDefinations(definations){
21
- return "";
91
+ dropColumn(table){
92
+ /*
93
+ COLUMNS CANNOT BE DROPPED - RULES
94
+ has unique constraint
95
+ is indexed
96
+ appears in a view
97
+ */
98
+ return `ALTER TABLE ${table.tableName} DROP COLUMN ${table.name}`
99
+ }
100
+
101
+ insertInto(name, table){
102
+ return `INSERT INTO ${name} (${this.#getTableColumns(table)})
103
+ SELECT ${this.#getTableColumns(table)} FROM ${this.tempTableName}`;
22
104
  }
23
105
 
24
- createTable(){
25
- `CREATE TABLE devices (
26
- name TEXT NOT NULL,
27
- model TEXT NOT NULL,
28
- Serial INTEGER NOT NULL UNIQUE
29
- );`
106
+ createTable(table){
107
+ var queryVar = "";
108
+ for (var key in table) {
109
+ if(typeof table[key] === "object"){
110
+ queryVar += `${this.#columnMapping(table[key])}, `;
111
+ }
112
+ }
113
+
114
+ return `CREATE TABLE ${table.__name} (${queryVar.replace(/,\s*$/, "")});`;
30
115
 
31
116
  /*
32
117
  INTEGER PRIMARY KEY AUTOINCREMENT
@@ -45,26 +130,24 @@ class migrationSQLiteQuery {
45
130
 
46
131
 
47
132
  dropTable(name){
48
-
133
+ return `DROP TABLE ${name}`
49
134
  }
50
135
 
51
- dropIndex(){
52
-
53
- }
54
- //"dbo.People", "Location"
55
- alterColumn(){
56
-
136
+ renameTable(table){
137
+ return `ALTER TABLE ${table.tableName} RENAME TO ${table.newName}`;
57
138
  }
58
139
 
59
- renameColumn(){
60
- `ALTER TABLE existing_table
61
- RENAME TO new_table;`
140
+ renameColumn(table){
141
+ return `ALTER TABLE ${table.tableName} RENAME COLUMN ${table.name} TO ${table.newName}`
62
142
  }
63
143
 
64
144
 
65
145
  }
66
146
 
67
147
 
148
+ module.exports = migrationSQLiteQuery;
149
+
150
+
68
151
  /*
69
152
  ADDING NEW COLUMN SQLITE
70
153
  There are some restrictions on the new column:
@@ -1,75 +1,84 @@
1
- const os = require('os');
1
+
2
2
 
3
3
  // https://channel9.msdn.com/Blogs/EF/Migrations-Under-the-Hood
4
+ // version 0.0.3
4
5
 
6
+ const os = require('os');
5
7
  class MigrationTemplate {
6
- up = ''
7
- down = ''
8
+
8
9
  constructor(name) {
9
- this.name = name;
10
+ this.name = name;
10
11
  }
11
12
 
13
+ #up = ''
14
+ #down = ''
15
+
12
16
  get(){
13
17
  return `
14
- class ${this.name} extends Schema {
18
+
19
+ var masterrecord = require('masterrecord');
20
+
21
+ class ${this.name} extends masterrecord.schema {
15
22
  constructor(context){
16
23
  super(context);
17
24
  }
18
25
 
19
26
  up(table){
20
- ${this.up}
27
+ this.init(table);
28
+ ${this.#up}
21
29
  }
22
30
 
23
31
  down(table){
24
- ${this.down}
32
+ this.init(table);
33
+ ${this.#down}
25
34
  }
26
35
  }
27
36
  module.exports = ${this.name};
28
37
  `
29
38
  }
30
39
 
31
- alterColumn(type, name){
40
+ alterColumn(type, name, parent){
32
41
  if(type === "up"){
33
- this.up += os.EOL + ` this.alterColumn(table.${name});`
42
+ this.#up += os.EOL + ` this.alterColumn(table.${parent}.${name});`
34
43
  }
35
44
  else{
36
- this.down += os.EOL + ` this.alterColumn(table.${name});`
45
+ this.#down += os.EOL + ` this.alterColumn(table.${parent}.${name});`
37
46
  }
38
47
  }
39
48
  createTable(type, name){
40
49
  if(type === "up"){
41
- this.up += os.EOL + ` this.createTable(table.${name});`
50
+ this.#up += os.EOL + ` this.createTable(table.${name});`
42
51
  }
43
52
  else{
44
- this.down += os.EOL + ` this.createTable(table.${name});`
53
+ this.#down += os.EOL + ` this.createTable(table.${name});`
45
54
  }
46
55
  }
47
56
 
48
- addColumn(type, name){
57
+ addColumn(type, name, parent){
49
58
  if(type === "up"){
50
- this.up += os.EOL + ` this.addColumn(table.${name});`
59
+ this.#up += os.EOL + ` this.addColumn(table.${parent}.${name});`
51
60
  }
52
61
  else{
53
- this.down += os.EOL + ` this.addColumn(table.${name});`
62
+ this.#down += os.EOL + ` this.addColumn(table.${parent}.${name});`
54
63
  }
55
64
  }
56
65
 
57
66
 
58
67
  dropTable(type, name){
59
68
  if(type === "up"){
60
- this.down += os.EOL + ` this.droptable(table.${name});`
69
+ this.#down += os.EOL + ` this.droptable(table.${name});`
61
70
  }
62
71
  else{
63
- this.down += os.EOL + ` this.droptable(table.${name});`
72
+ this.#down += os.EOL + ` this.droptable(table.${name});`
64
73
  }
65
74
  }
66
75
 
67
- dropColumn(type, name){
76
+ dropColumn(type, name, parent){
68
77
  if(type === "up"){
69
- this.up += os.EOL + ` this.dropColumn(table.${name});`
78
+ this.#up += os.EOL + ` this.dropColumn(table.${parent}.${name});`
70
79
  }
71
80
  else{
72
- this.down += os.EOL + ` this.dropColumn(table.${name});`
81
+ this.#down += os.EOL + ` this.dropColumn(table.${parent}.${name});`
73
82
  }
74
83
  }
75
84
 
@@ -1,4 +1,4 @@
1
- // version 0.0.4
1
+ // version 0.0.5
2
2
  // learn more about seeding info - https://www.pauric.blog/Database-Updates-and-Migrations-with-Entity-Framework/
3
3
 
4
4
  var fs = require('fs');
@@ -11,66 +11,49 @@ var globSearch = require("glob");
11
11
  // node masterrecord add-migration josh C:\Users\rbatista\Downloads\kollege\freshmen\app\models\context
12
12
  class Migrations{
13
13
 
14
- getContext(executedLocation, contextFileName){
15
- var search = `${executedLocation}/**/*${contextFileName}.js`
16
- var files = globSearch.sync(search, executedLocation);
17
- var file = files[0];
18
- var context = require(file);
19
- return {
20
- context : context,
21
- fileLocation : file
22
- }
23
- }
24
-
25
- createSnapShot(snap){
26
- var migrationsDirectory = `${snap.executedLocation}/db/migrations`;
27
- if (!fs.existsSync(migrationsDirectory)){
28
- fs.mkdirSync(migrationsDirectory);
29
- }
30
-
31
- var content = {
32
- contextLocation: snap.file,
33
- migrationFolder: `${snap.executedLocation}/db/migrations`,
34
- snapShotLocation: `${snap.executedLocation}/db/migrations/${snap.contextFileName}_contextSnapShot.json`,
35
- schema : snap.context.__entities
36
- };
37
-
38
- const jsonContent = JSON.stringify(content, null, 2);
39
- try{
40
- // will replace the whole file if it exist
41
- fs.writeFileSync(`${migrationsDirectory}/${snap.contextFileName}_contextSnapShot.json`, jsonContent);
42
- }catch (e){
43
- console.log("Cannot write file ", e);
44
- }
45
- }
46
-
47
- organizeSchemaByTables(oldSchema, newSchema){
14
+ #organizeSchemaByTables(oldSchema, newSchema){
48
15
  var tables = []
49
-
50
- newSchema.forEach(function (item, index) {
51
-
52
- var table = {
53
- name: item["__name"],
54
- old: null,
55
- new :item,
56
- newColumns : [],
57
- deletedColumns : [],
58
- updatedColumns : []
59
- }
60
-
61
- oldSchema.forEach(function (oldItem, index) {
62
- var oldItemName = oldItem["__name"];
63
- if(table.name === oldItemName){
64
- table.old = oldItem;
65
- tables.push(table);
16
+ if(oldSchema.length === 0){
17
+ newSchema.forEach(function (item, index) {
18
+ var table = {
19
+ name: item["__name"],
20
+ new :item,
21
+ old : {},
22
+ newColumns : [],
23
+ newTables : [],
24
+ deletedColumns : [],
25
+ updatedColumns : []
66
26
  }
27
+ tables.push(table);
67
28
  });
68
- });
29
+ }
30
+ else{
31
+ newSchema.forEach(function (item, index) {
32
+ var table = {
33
+ name: item["__name"],
34
+ old: null,
35
+ new :item,
36
+ newColumns : [],
37
+ newTables : [],
38
+ deletedColumns : [],
39
+ updatedColumns : []
40
+ }
41
+
42
+ oldSchema.forEach(function (oldItem, index) {
43
+ var oldItemName = oldItem["__name"];
44
+ if(table.name === oldItemName){
45
+ table.old = oldItem;
46
+ tables.push(table);
47
+ }
48
+ });
49
+
50
+ });
51
+ }
69
52
 
70
53
  return tables;
71
54
  }
72
55
 
73
- findDeletedColumnsInTables(tables){
56
+ #findDeletedColumns(tables){
74
57
  tables.forEach(function (item, index) {
75
58
  var deletedColumn = null;
76
59
  if(item.new && item.old){
@@ -92,123 +75,193 @@ class Migrations{
92
75
  return tables;
93
76
  }
94
77
 
95
- findUpdatedColumns(tables){
78
+ #findUpdatedColumns(tables){
96
79
  tables.forEach(function (item, index) {
97
80
  var UD = diff.updatedDiff(item.old, item.new);
98
81
  const isEmpty = Object.keys(UD).length === 0;
99
82
  if(!isEmpty){
100
- item.updatedColumns.push(diff.updatedDiff(item.old, item.new));
83
+ for (var key in UD) {
84
+ var tableChanges = {
85
+ changes : UD[key],
86
+ table : item.new[key],
87
+ tableName : item.name
88
+ };
89
+ item.updatedColumns.push(tableChanges);
90
+ }
101
91
  }
102
92
 
103
93
  });
104
94
  return tables;
105
95
  }
106
96
 
107
- findNewColumnsInTables(tables){
97
+ #findNewColumns(tables){
108
98
  tables.forEach(function (item, index) {
109
- var newColumn = null;
110
99
  if(item.new && item.old){
111
100
  Object.keys(item.new).forEach(function (key) {
112
- var value = item.new[key].name;
113
- newColumn = null;
114
- Object.keys(item.old).forEach(function (oldKey) {
115
- var oldValue = item.old[oldKey].name;
116
- if(value === oldValue){
117
- newColumn = value;
101
+ if(typeof item.new[key] === "object"){
102
+ var value = item.new[key].name;
103
+ var columnNotFound = false;
104
+ Object.keys(item.old).forEach(function (oldKey) {
105
+ if(typeof item.old[oldKey] === "object"){
106
+ var oldValue = item.old[oldKey].name;
107
+ if(value === oldValue){
108
+ columnNotFound = true;
109
+ }
110
+ }
111
+ });
112
+
113
+ if(columnNotFound === false){
114
+ // this means it did not find the column
115
+ item.newColumns.push(value);
118
116
  }
119
- });
120
- if(newColumn === null){
121
- item.newColumns.push(value);
122
117
  }
118
+
123
119
  });
124
120
  }
121
+ else{
122
+ console.log("Table object has no old or new values");
123
+ }
125
124
  });
126
125
  return tables;
127
126
  }
128
127
 
128
+ #findNewTables(tables){
129
+ // find new tables
130
+ tables.forEach(function (item, index) {
131
+ if(item.new && item.old){
132
+ if(Object.keys(item.old).length === 0){
133
+ item.newTables.push(item);
134
+ }
135
+ }else{
136
+ console.log("Cannot find NEW or and Old Objects");
137
+ }
138
+
139
+ });
140
+ return tables;
141
+ }
142
+
129
143
  // build table to build new migration snapshot
130
- buildMigrationObject(oldSchema, newSchema){
131
- var tables = this.organizeSchemaByTables(oldSchema, newSchema);
132
- tables = this.findNewColumnsInTables(tables);
133
- tables = this.findDeletedColumnsInTables(tables);
134
- tables = this.findUpdatedColumns(tables);
144
+ #buildMigrationObject(oldSchema, newSchema){
145
+ var tables = this.#organizeSchemaByTables(oldSchema, newSchema);
146
+ tables = this.#findNewTables(tables);
147
+ tables = this.#findNewColumns(tables);
148
+ tables = this.#findDeletedColumns(tables);
149
+ tables = this.#findUpdatedColumns(tables);
135
150
  return tables;
136
151
  }
137
152
 
153
+
154
+
155
+ findContext(executedLocation, contextFileName){
156
+ var search = `${executedLocation}/**/*${contextFileName}.js`
157
+ var files = globSearch.sync(search, executedLocation);
158
+ var file = files[0];
159
+ var context = require(file);
160
+ return {
161
+ context : context,
162
+ fileLocation : file
163
+ }
164
+ }
165
+
166
+ createSnapShot(snap){
167
+ var migrationsDirectory = `${snap.executedLocation}/db/migrations`;
168
+ if (!fs.existsSync(migrationsDirectory)){
169
+ fs.mkdirSync(migrationsDirectory);
170
+ }
171
+
172
+ var content = {
173
+ contextLocation: snap.file,
174
+ migrationFolder: `${snap.executedLocation}/db/migrations`,
175
+ snapShotLocation: `${snap.executedLocation}/db/migrations/${snap.contextFileName}_contextSnapShot.json`,
176
+ schema : snap.contextEntities
177
+ };
178
+
179
+ const jsonContent = JSON.stringify(content, null, 2);
180
+ try{
181
+ // will replace the whole file if it exist
182
+ fs.writeFileSync(`${migrationsDirectory}/${snap.contextFileName}_contextSnapShot.json`, jsonContent);
183
+ }catch (e){
184
+ console.log("Cannot write file ", e);
185
+ }
186
+ }
187
+
138
188
  //
139
- callMigrationUp(oldSchema, newSchema){
140
- var tableArray =[];
141
- var tables = this.buildMigrationObject(oldSchema, newSchema);
189
+ up(oldSchema, newSchema){
190
+ var tableObj = {}
191
+ var tables = this.#buildMigrationObject(oldSchema, newSchema);
142
192
  tables.forEach(function (item, index) {
143
-
144
193
  // add new columns for table
145
- item.newColumns.forEach(function (column, index) {
146
- tableArray.push(tables[column]);
194
+ var columnInfo = tables[index];
195
+
196
+ item.newColumns.forEach(function (column, ind) {
197
+ columnInfo.new[column].tableName = item.name;
198
+ tableObj[column] = columnInfo.new[column];
147
199
  });
148
200
 
149
- item.deletedColumns.forEach(function (column, index) {
150
- tableArray.push(tables[column]);
201
+ item.newTables.forEach(function (column, ind) {
202
+ tableObj[item.name] = columnInfo.new;
151
203
  });
152
204
 
153
- item.updatedColumns.forEach(function (column, index) {
154
- tableArray.push(tables[column]);
205
+ item.deletedColumns.forEach(function (column, ind) {
206
+ columnInfo.old[column].tableName = item.name;
207
+ tableObj[column] = columnInfo.old[column];
155
208
  });
156
209
 
157
- if(item.old === null){
158
- tableArray.push(tables[column]);
210
+ item.updatedColumns.forEach(function (column, ind) {
211
+ tableObj[column.table.name] = column;
212
+ });
159
213
 
160
- }
161
214
  if(item.new === null){
162
- tableArray.push(tables[column]);
215
+ columnInfo.old.tableName = item.name;
216
+ tableObj[column] = columnInfo.old;
163
217
  }
164
218
 
219
+ tableObj.___table = item;
165
220
  });
166
-
167
- return tableArray;
221
+ return tableObj;
168
222
  }
169
223
 
170
- buildMigrationTemplate(name, oldSchema, newSchema){
171
-
224
+ template(name, oldSchema, newSchema){
172
225
  var MT = new MigrationTemplate(name);
173
- var tables = this.buildMigrationObject(oldSchema, newSchema);
226
+ var tables = this.#buildMigrationObject(oldSchema, newSchema);
174
227
  tables.forEach(function (item, index) {
175
228
  // add new columns for table
176
229
  item.newColumns.forEach(function (column, index) {
177
- MT.addColumn("up", column);
178
- MT.dropColumn("down", column);
230
+ MT.addColumn("up", column, item.name);
231
+ MT.dropColumn("down", column, item.name);
232
+ });
233
+
234
+ item.newTables.forEach(function (column, ind) {
235
+ MT.createTable("up", item.name);
236
+ MT.dropTable("down", item.name);
179
237
  });
180
238
 
181
239
  item.deletedColumns.forEach(function (column, index) {
182
- MT.dropColumn("up", column);
183
- MT.addColumn("down",column);
240
+ MT.dropColumn("up", column, item.name);
241
+ MT.addColumn("down",column, item.name);
184
242
  });
185
243
 
186
244
  item.updatedColumns.forEach(function (column, index) {
187
- MT.alterColumn("up", column);
188
- MT.alterColumn("down", column)
245
+ const isEmpty = Object.keys(column).length === 0;
246
+ if(!isEmpty){
247
+ MT.alterColumn("up", column.table.name, item.name);
248
+ MT.alterColumn("down", column.table.name, item.name);
249
+ }
189
250
  });
190
251
 
191
252
  if(item.old === null){
192
- MT.createTable("up", column);
193
- MT.dropTable("down", column);
253
+ MT.createTable("up", column, item.name);
254
+ MT.dropTable("down", column, item.name);
194
255
 
195
256
  }
196
257
  if(item.new === null){
197
- MT.dropTable("up", column);
198
- MT.createTable("down", column);
258
+ MT.dropTable("up", column, item.name);
259
+ MT.createTable("down", column, item.name);
199
260
  }
200
261
 
201
262
  });
202
263
 
203
264
  return MT.get();
204
-
205
-
206
- }
207
-
208
- migrationCodeGenerator(name, column, migrationDate){
209
- // will create migration file with data needed
210
- // using the migration template
211
-
212
265
  }
213
266
 
214
267
 
@@ -1,63 +1,78 @@
1
- // version 1
2
- var fs = require('fs');
3
-
4
- var table = {
5
- email : {
6
- name: "auth",
7
- column : "email",
8
- rules: {
9
- "type": "integer",
10
- "primary": true,
11
- "nullable": false,
12
- "unique": true,
13
- "auto": true,
14
- "cascadeOnDelete": true,
15
- "lazyLoading": true,
16
- "isNavigational": false
1
+ // version 0.0.3
2
+ class schema{
17
3
 
4
+ constructor(context){
5
+ this.context = new context();
18
6
  }
19
- }
20
- }
21
7
 
22
8
 
23
- class schema{
24
- // TODO : check what database we are using
25
- // based on the database you can make the call to update the database.
26
-
27
-
28
- constructor(context){
29
- this.context = context;
9
+ init(table){
10
+ this.fullTable = table.___table;
30
11
  }
31
12
 
32
13
  // create obj to convert into create sql
33
14
  addColumn(table){
34
15
  if(this.context.isSQite){
35
16
  var sqliteQuery = require("./migrationSQLiteQuery");
36
- var query = sqliteQuery.addColumn(table);
37
- this.context.db.prepare(query).all();
17
+ var queryBuilder = new sqliteQuery();
18
+ var queryObj = queryBuilder.alterColumn(this.fullTable.new, table);
19
+ for (var key in queryObj) {
20
+ var query = queryObj[key];
21
+ this.context._execute(query);
22
+ }
38
23
  }
39
24
  // add column to database
40
25
  }
41
26
 
42
- createTable(name, columns){
43
-
27
+ dropColumn(table){
28
+ if(this.fullTable){
29
+ // drop column
30
+ if(this.context.isSQite){
31
+ var sqliteQuery = require("./migrationSQLiteQuery");
32
+ var queryBuilder = new sqliteQuery();
33
+ var query = queryBuilder.dropColumn(table);
34
+ this.context._execute(query);
35
+ }
36
+ }else{
37
+ console.log("Must call the addTable function.");
38
+ }
44
39
  }
45
-
46
- dropColumn(tableName, columnName){
47
- // drop column
48
-
40
+
41
+ createTable(table){
42
+ if(this.context.isSQite){
43
+ var sqliteQuery = require("./migrationSQLiteQuery");
44
+ var queryBuilder = new sqliteQuery();
45
+ var query = queryBuilder.createTable(table);
46
+ this.context._execute(query);
47
+ }
49
48
  }
50
49
 
51
- dropTable(name){
52
50
 
51
+ dropTable(table){
52
+ if(this.context.isSQite){
53
+ var sqliteQuery = require("./migrationSQLiteQuery");
54
+ var queryBuilder = new sqliteQuery();
55
+ var query = queryBuilder.dropTable(table.__name);
56
+ this.context._execute(query);
57
+ }
53
58
  }
54
59
 
55
- dropIndex(){
56
-
57
- }
58
- //"dbo.People", "Location"
59
- alterColumn(){
60
60
 
61
+ //"dbo.People", "Location"
62
+ alterColumn(table){
63
+ if(this.fullTable){
64
+ if(this.context.isSQite){
65
+ var sqliteQuery = require("./migrationSQLiteQuery");
66
+ var queryBuilder = new sqliteQuery();
67
+ var queryObj = queryBuilder.alterColumn(this.fullTable.new, table);
68
+ for (var key in queryObj) {
69
+ var query = queryObj[key];
70
+ this.context._execute(query);
71
+ }
72
+ }
73
+ }else{
74
+ console.log("Must call the addTable function.");
75
+ }
61
76
  }
62
77
 
63
78
  renameColumn(){
@@ -67,24 +82,8 @@ class schema{
67
82
  seed(){
68
83
 
69
84
  }
70
-
71
- // will get the data and create the file
72
- done(){
73
-
74
-
75
- }
76
85
 
77
86
  }
78
87
 
79
88
 
80
- /*
81
- up and down function..
82
- on commmand line call of run migrations with folder location of context. it will
83
- load context and all the objects.
84
- it will then match objects with migration data.
85
- if it's a new item it will generate a new migration dependent on what comes from migration.
86
-
87
-
88
- */
89
-
90
89
  module.exports = schema;
package/SQLLiteEngine.js CHANGED
@@ -1,3 +1,4 @@
1
+ // Version 0.0.1
1
2
  var tools = require('masterrecord/Tools');
2
3
 
3
4
  class SQLLiteEngine {
package/context.js CHANGED
@@ -1,3 +1,4 @@
1
+ // Version 0.0.1
1
2
 
2
3
  var modelBuilder = require('./Entity/EntityModelBuilder');
3
4
  var query = require('masterrecord/QueryLanguage/queryMethods');
@@ -9,7 +10,7 @@ var deleteManager = require('./DeleteManager');
9
10
  var globSearch = require("glob");
10
11
 
11
12
 
12
- class Context {
13
+ class context {
13
14
  _isModelValid = {
14
15
  isValid: true,
15
16
  errors: []
@@ -68,7 +69,7 @@ class Context {
68
69
  const connection = mysql.createConnection(env);
69
70
  connection.connect();
70
71
  db.__name = sqlName;
71
- this._SQLEngine = new MYSQLEngine();
72
+ this._MYSQLEngine = new MYSQLEngine();
72
73
  return connection;
73
74
 
74
75
  }
@@ -149,7 +150,7 @@ class Context {
149
150
  useMySql(options, rootFolderLocation){
150
151
  if(options !== undefined){
151
152
  this.db = this.__mysqlInit(options, "mysql");
152
- this._SQLEngine.setDB(this.db, "mysql");
153
+ this._MYSQLEngine.setDB(this.db, "mysql");
153
154
  return this;
154
155
  }
155
156
  else{
@@ -175,39 +176,41 @@ class Context {
175
176
  try{
176
177
  var tracked = this.__trackedEntities;
177
178
  // start transaction
178
- this._SQLEngine.startTransaction();
179
- for (var model in tracked) {
180
- var currentModel = tracked[model];
181
- switch(currentModel.__state) {
182
- case "insert":
183
- var insert = new insertManager(this._SQLEngine, this._isModelValid, this.__entities);
184
- insert.init(currentModel);
185
-
186
- break;
187
- case "modified":
188
- if(currentModel.__dirtyFields.length > 0){
189
- var cleanCurrentModel = tools.removePrimarykeyandVirtual(currentModel, currentModel._entity);
190
- // build columns equal to value string
191
- var argu = this._SQLEngine._buildSQLEqualTo(cleanCurrentModel);
192
- var primaryKey = tools.getPrimaryKeyObject(cleanCurrentModel.__entity);
193
- var sqlUpdate = {tableName: cleanCurrentModel.__entity.__name, arg: argu, primaryKey : primaryKey, primaryKeyValue : cleanCurrentModel[primaryKey] };
194
- this._SQLEngine.update(sqlUpdate);
195
- }
196
- else{
197
- console.log("Tracked entity modified with no values being changed");
198
- }
199
-
200
- // code block
201
- break;
202
- case "delete":
203
- var deleteObject = new deleteManager(this._SQLEngine, this.__entities);
204
- deleteObject.init(currentModel);
205
-
206
- break;
207
- }
179
+ if(this.isSQite){
180
+ this._SQLEngine.startTransaction();
181
+ for (var model in tracked) {
182
+ var currentModel = tracked[model];
183
+ switch(currentModel.__state) {
184
+ case "insert":
185
+ var insert = new insertManager(this._SQLEngine, this._isModelValid, this.__entities);
186
+ insert.init(currentModel);
187
+
188
+ break;
189
+ case "modified":
190
+ if(currentModel.__dirtyFields.length > 0){
191
+ var cleanCurrentModel = tools.removePrimarykeyandVirtual(currentModel, currentModel._entity);
192
+ // build columns equal to value string
193
+ var argu = this._SQLEngine._buildSQLEqualTo(cleanCurrentModel);
194
+ var primaryKey = tools.getPrimaryKeyObject(cleanCurrentModel.__entity);
195
+ var sqlUpdate = {tableName: cleanCurrentModel.__entity.__name, arg: argu, primaryKey : primaryKey, primaryKeyValue : cleanCurrentModel[primaryKey] };
196
+ this._SQLEngine.update(sqlUpdate);
197
+ }
198
+ else{
199
+ console.log("Tracked entity modified with no values being changed");
200
+ }
201
+
202
+ // code block
203
+ break;
204
+ case "delete":
205
+ var deleteObject = new deleteManager(this._SQLEngine, this.__entities);
206
+ deleteObject.init(currentModel);
207
+
208
+ break;
209
+ }
210
+ }
211
+ this.__clearErrorHandler();
212
+ this._SQLEngine.endTransaction();
208
213
  }
209
- this.__clearErrorHandler();
210
- this._SQLEngine.endTransaction();
211
214
  }
212
215
 
213
216
  catch(error){
@@ -222,6 +225,13 @@ class Context {
222
225
  return true;
223
226
  }
224
227
 
228
+
229
+ _execute(query){
230
+ if(this.isSQite){
231
+ this._SQLEngine._execute(query);
232
+ }
233
+ }
234
+
225
235
  // TODO: WHY WE HAVE DOUBLE TRACKED OBJECTS - LOOP THROUGH ALL TRACKED OBJECTS
226
236
  __track(model){
227
237
  this.__trackedEntities.push(model);
@@ -245,4 +255,4 @@ class Context {
245
255
  }
246
256
 
247
257
 
248
- module.exports = Context;
258
+ module.exports = context;
package/package.json CHANGED
@@ -6,7 +6,7 @@
6
6
  "glob" : "^8.0.3",
7
7
  "deep-object-diff" : "^1.1.7"
8
8
  },
9
- "version": "0.0.31",
9
+ "version": "0.0.33",
10
10
  "description": "An Object-relational mapping for the Master framework. Master Record connects classes to relational database tables to establish a database with almost zero-configuration ",
11
11
  "homepage": "https://github.com/Tailor/MasterRecord#readme",
12
12
  "repository": {
@@ -1 +0,0 @@
1
- // will be the template used to create the scheme section
@@ -1,34 +0,0 @@
1
- class temp {
2
-
3
-
4
- hatml =
5
- buildMOdal(className, header, body){
6
-
7
- `
8
- Copy
9
- <div class="modal" tabindex="-1" role="dialog" ${className}>
10
- <div class="modal-dialog" role="document">
11
- <div class="modal-content">
12
- <div class="modal-header">
13
- ${ buildheader(header)}
14
- <button type="button" class="close" data-dismiss="modal" aria-label="Close">
15
- <span aria-hidden="true">&times;</span>
16
- </button>
17
- </div>
18
- <div class="modal-body">
19
- ${body}
20
- </div>
21
- <div class="modal-footer">
22
- <button type="button" class="btn btn-primary">Save changes</button>
23
- <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
24
- </div>
25
- </div>
26
- </div>
27
- </div>`
28
-
29
- }
30
-
31
- buildheader(title){
32
- return ` <h5 class="modal-title">${title}</h5>`
33
- }
34
- }