fib-orm 1.4.2 → 2.0.0

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.
Files changed (295) hide show
  1. package/License +1 -1
  2. package/README.md +53 -0
  3. package/lib/cli/commands/ddlFrom.d.ts +2 -0
  4. package/lib/cli/commands/ddlFrom.js +74 -0
  5. package/lib/cli/commands/dumpModel.d.ts +2 -0
  6. package/lib/cli/commands/dumpModel.js +106 -0
  7. package/lib/cli/commands/escape.d.ts +2 -0
  8. package/lib/cli/commands/escape.js +68 -0
  9. package/lib/cli/commands/spinner.d.ts +2 -0
  10. package/lib/cli/commands/spinner.js +36 -0
  11. package/lib/cli/commands/upgrade.d.ts +2 -0
  12. package/lib/cli/commands/upgrade.js +65 -0
  13. package/lib/cli/helpers/ddl.d.ts +17 -0
  14. package/lib/cli/helpers/ddl.js +55 -0
  15. package/lib/cli/helpers/package.d.ts +26 -0
  16. package/lib/cli/helpers/package.js +56 -0
  17. package/lib/cli/index.d.ts +2 -0
  18. package/lib/cli/index.js +18 -0
  19. package/lib/codepoints-map.json +762 -0
  20. package/lib/db-driver/Typo.d.ts +112 -0
  21. package/lib/db-driver/Typo.js +1 -0
  22. package/lib/db-driver/built-ins/base.class.d.ts +96 -0
  23. package/lib/db-driver/built-ins/base.class.js +186 -0
  24. package/lib/db-driver/built-ins/driver-dm.d.ts +18 -0
  25. package/lib/db-driver/built-ins/driver-dm.js +53 -0
  26. package/lib/db-driver/built-ins/driver-mongodb.d.ts +24 -0
  27. package/lib/db-driver/built-ins/driver-mongodb.js +46 -0
  28. package/lib/db-driver/built-ins/driver-mysql.d.ts +18 -0
  29. package/lib/db-driver/built-ins/driver-mysql.js +37 -0
  30. package/lib/db-driver/built-ins/driver-postgresql.d.ts +22 -0
  31. package/lib/db-driver/built-ins/driver-postgresql.js +76 -0
  32. package/lib/db-driver/built-ins/driver-redis.d.ts +12 -0
  33. package/lib/db-driver/built-ins/driver-redis.js +35 -0
  34. package/lib/db-driver/built-ins/driver-sqlite.d.ts +17 -0
  35. package/lib/db-driver/built-ins/driver-sqlite.js +34 -0
  36. package/lib/db-driver/index.d.ts +3 -0
  37. package/lib/db-driver/index.js +4 -0
  38. package/lib/db-driver/utils.d.ts +14 -0
  39. package/lib/db-driver/utils.js +187 -0
  40. package/lib/knex/deps/tarn/dist/PendingOperation.d.ts +12 -0
  41. package/lib/knex/deps/tarn/dist/PendingOperation.js +48 -0
  42. package/lib/knex/deps/tarn/dist/Pool.d.ts +97 -0
  43. package/lib/knex/deps/tarn/dist/Pool.js +516 -0
  44. package/lib/knex/deps/tarn/dist/PromiseInspection.d.ts +16 -0
  45. package/lib/knex/deps/tarn/dist/PromiseInspection.js +21 -0
  46. package/lib/knex/deps/tarn/dist/Resource.d.ts +9 -0
  47. package/lib/knex/deps/tarn/dist/Resource.js +19 -0
  48. package/lib/knex/deps/tarn/dist/TimeoutError.d.ts +2 -0
  49. package/lib/knex/deps/tarn/dist/TimeoutError.js +5 -0
  50. package/lib/knex/deps/tarn/dist/tarn.d.ts +3 -0
  51. package/lib/knex/deps/tarn/dist/tarn.js +10 -0
  52. package/lib/knex/deps/tarn/dist/utils.d.ts +14 -0
  53. package/lib/knex/deps/tarn/dist/utils.js +60 -0
  54. package/lib/knex/knex.d.ts +2 -0
  55. package/lib/knex/knex.js +3 -0
  56. package/lib/knex/sandbox.d.ts +4 -0
  57. package/lib/knex/sandbox.js +22 -0
  58. package/lib/orm/Adapters.d.ts +3 -0
  59. package/lib/orm/Adapters.js +44 -0
  60. package/lib/orm/AggregateFunctions.d.ts +3 -0
  61. package/lib/orm/AggregateFunctions.js +176 -0
  62. package/lib/orm/Associations/Extend.d.ts +22 -0
  63. package/lib/orm/Associations/Extend.js +274 -0
  64. package/lib/orm/Associations/Many.d.ts +17 -0
  65. package/lib/orm/Associations/Many.js +569 -0
  66. package/lib/orm/Associations/One.d.ts +16 -0
  67. package/lib/orm/Associations/One.js +310 -0
  68. package/lib/orm/Associations/_utils.d.ts +15 -0
  69. package/lib/orm/Associations/_utils.js +52 -0
  70. package/lib/orm/ChainFind.d.ts +3 -0
  71. package/lib/orm/ChainFind.js +327 -0
  72. package/lib/orm/ChainInstance.d.ts +6 -0
  73. package/lib/orm/ChainInstance.js +73 -0
  74. package/lib/orm/Debug.d.ts +2 -0
  75. package/lib/orm/Debug.js +17 -0
  76. package/lib/orm/Drivers/DB/base.d.ts +3 -0
  77. package/lib/orm/Drivers/DB/base.js +3 -0
  78. package/lib/orm/Drivers/DB/dm.d.ts +11 -0
  79. package/lib/orm/Drivers/DB/dm.js +23 -0
  80. package/lib/orm/Drivers/DB/mysql.d.ts +11 -0
  81. package/lib/orm/Drivers/DB/mysql.js +23 -0
  82. package/lib/orm/Drivers/DB/postgres.d.ts +11 -0
  83. package/lib/orm/Drivers/DB/postgres.js +22 -0
  84. package/lib/orm/Drivers/DB/sqlite3.d.ts +16 -0
  85. package/lib/orm/Drivers/DB/sqlite3.js +39 -0
  86. package/lib/orm/Drivers/DML/_ddl-sql.d.ts +3 -0
  87. package/lib/orm/Drivers/DML/_ddl-sql.js +51 -0
  88. package/lib/orm/Drivers/DML/_dml-helpers.d.ts +19 -0
  89. package/lib/orm/Drivers/DML/_dml-helpers.js +51 -0
  90. package/lib/orm/Drivers/DML/_shared.d.ts +9 -0
  91. package/lib/orm/Drivers/DML/_shared.js +38 -0
  92. package/lib/orm/Drivers/DML/_utils.d.ts +8 -0
  93. package/lib/orm/Drivers/DML/_utils.js +67 -0
  94. package/lib/orm/Drivers/DML/constants.d.ts +3 -0
  95. package/lib/orm/Drivers/DML/constants.js +2 -0
  96. package/lib/orm/Drivers/DML/dm.d.ts +2 -0
  97. package/lib/orm/Drivers/DML/dm.js +293 -0
  98. package/lib/orm/Drivers/DML/index.d.ts +4 -0
  99. package/lib/orm/Drivers/DML/index.js +6 -0
  100. package/lib/orm/Drivers/DML/mysql.d.ts +2 -0
  101. package/lib/orm/Drivers/DML/mysql.js +251 -0
  102. package/lib/orm/Drivers/DML/postgres.d.ts +3 -0
  103. package/lib/orm/Drivers/DML/postgres.js +276 -0
  104. package/lib/orm/Drivers/DML/sqlite.d.ts +2 -0
  105. package/lib/orm/Drivers/DML/sqlite.js +266 -0
  106. package/lib/orm/Error.d.ts +11 -0
  107. package/lib/orm/Error.js +40 -0
  108. package/lib/orm/Helpers.d.ts +35 -0
  109. package/lib/orm/Helpers.js +233 -0
  110. package/lib/orm/Hook.d.ts +13 -0
  111. package/lib/orm/Hook.js +99 -0
  112. package/lib/orm/Instance.d.ts +2 -0
  113. package/lib/orm/Instance.js +697 -0
  114. package/lib/orm/LazyLoad.d.ts +4 -0
  115. package/lib/orm/LazyLoad.js +76 -0
  116. package/lib/orm/Model.d.ts +7 -0
  117. package/lib/orm/Model.js +971 -0
  118. package/lib/orm/ORM.d.ts +37 -0
  119. package/lib/orm/ORM.js +241 -0
  120. package/lib/orm/Patch/fib-cache.d.ts +40 -0
  121. package/lib/orm/Patch/fib-cache.js +2 -0
  122. package/lib/orm/Patch/plugin.d.ts +4 -0
  123. package/lib/orm/Patch/plugin.js +13 -0
  124. package/lib/orm/Property.d.ts +9 -0
  125. package/lib/orm/Property.js +71 -0
  126. package/lib/orm/Settings.d.ts +42 -0
  127. package/lib/orm/Settings.js +119 -0
  128. package/lib/orm/Singleton.d.ts +5 -0
  129. package/lib/orm/Singleton.js +72 -0
  130. package/lib/orm/Typo/Adapter.d.ts +5 -0
  131. package/lib/orm/Typo/Adapter.js +1 -0
  132. package/lib/orm/Typo/DMLDriver.d.ts +210 -0
  133. package/lib/orm/Typo/DMLDriver.js +1 -0
  134. package/lib/orm/Typo/Db.d.ts +38 -0
  135. package/lib/orm/Typo/Db.js +1 -0
  136. package/lib/orm/Typo/Error.d.ts +31 -0
  137. package/lib/orm/Typo/Error.js +1 -0
  138. package/lib/orm/Typo/ORM.d.ts +233 -0
  139. package/lib/orm/Typo/ORM.js +3 -0
  140. package/lib/orm/Typo/Validators.d.ts +32 -0
  141. package/lib/orm/Typo/Validators.js +2 -0
  142. package/lib/orm/Typo/_common.d.ts +38 -0
  143. package/lib/orm/Typo/_common.js +1 -0
  144. package/lib/orm/Typo/assoc.d.ts +221 -0
  145. package/lib/orm/Typo/assoc.js +1 -0
  146. package/lib/orm/Typo/hook.d.ts +42 -0
  147. package/lib/orm/Typo/hook.js +1 -0
  148. package/lib/orm/Typo/instance.d.ts +157 -0
  149. package/lib/orm/Typo/instance.js +1 -0
  150. package/lib/orm/Typo/model.d.ts +313 -0
  151. package/lib/orm/Typo/model.js +6 -0
  152. package/lib/orm/Typo/patch.d.ts +31 -0
  153. package/lib/orm/Typo/patch.js +1 -0
  154. package/lib/orm/Typo/property.d.ts +57 -0
  155. package/lib/orm/Typo/property.js +1 -0
  156. package/lib/orm/Typo/query.d.ts +216 -0
  157. package/lib/orm/Typo/query.js +1 -0
  158. package/lib/orm/Typo/settings.d.ts +35 -0
  159. package/lib/orm/Typo/settings.js +5 -0
  160. package/lib/orm/Typo/synchronous.d.ts +47 -0
  161. package/lib/orm/Typo/synchronous.js +1 -0
  162. package/lib/orm/Utilities.d.ts +179 -0
  163. package/lib/orm/Utilities.js +975 -0
  164. package/lib/orm/Validators.d.ts +34 -0
  165. package/lib/orm/Validators.js +100 -0
  166. package/lib/orm/Where/common.d.ts +1 -0
  167. package/lib/orm/Where/common.js +7 -0
  168. package/lib/orm/Where/filterDate.d.ts +11 -0
  169. package/lib/orm/Where/filterDate.js +58 -0
  170. package/lib/orm/index.d.ts +68 -0
  171. package/lib/orm/index.js +157 -0
  172. package/lib/orm-core/callback.d.ts +12 -0
  173. package/lib/orm-core/callback.js +1 -0
  174. package/lib/orm-core/dialect.d.ts +80 -0
  175. package/lib/orm-core/dialect.js +1 -0
  176. package/lib/orm-core/error.d.ts +16 -0
  177. package/lib/orm-core/error.js +29 -0
  178. package/lib/orm-core/index.d.ts +6 -0
  179. package/lib/orm-core/index.js +6 -0
  180. package/lib/orm-core/sync.d.ts +12 -0
  181. package/lib/orm-core/sync.js +1 -0
  182. package/lib/orm-core/utils.d.ts +1 -0
  183. package/lib/orm-core/utils.js +5 -0
  184. package/lib/orm-property/Property.d.ts +78 -0
  185. package/lib/orm-property/Property.js +1 -0
  186. package/lib/orm-property/Utils.d.ts +9 -0
  187. package/lib/orm-property/Utils.js +13 -0
  188. package/lib/orm-property/customTypes.d.ts +2 -0
  189. package/lib/orm-property/customTypes.js +13 -0
  190. package/lib/orm-property/index.d.ts +10 -0
  191. package/lib/orm-property/index.js +22 -0
  192. package/lib/orm-property/transformer.d.ts +5 -0
  193. package/lib/orm-property/transformer.js +10 -0
  194. package/lib/orm-property/transformers/dm.d.ts +29 -0
  195. package/lib/orm-property/transformers/dm.js +237 -0
  196. package/lib/orm-property/transformers/index.d.ts +4 -0
  197. package/lib/orm-property/transformers/index.js +5 -0
  198. package/lib/orm-property/transformers/mysql.d.ts +102 -0
  199. package/lib/orm-property/transformers/mysql.js +261 -0
  200. package/lib/orm-property/transformers/postgresql.d.ts +54 -0
  201. package/lib/orm-property/transformers/postgresql.js +189 -0
  202. package/lib/orm-property/transformers/sqlite.d.ts +19 -0
  203. package/lib/orm-property/transformers/sqlite.js +171 -0
  204. package/lib/sql-ddl-sync/Dialects/dm.d.ts +40 -0
  205. package/lib/sql-ddl-sync/Dialects/dm.js +296 -0
  206. package/lib/sql-ddl-sync/Dialects/index.d.ts +7 -0
  207. package/lib/sql-ddl-sync/Dialects/index.js +7 -0
  208. package/lib/sql-ddl-sync/Dialects/mysql.d.ts +39 -0
  209. package/lib/sql-ddl-sync/Dialects/mysql.js +240 -0
  210. package/lib/sql-ddl-sync/Dialects/postgresql.d.ts +40 -0
  211. package/lib/sql-ddl-sync/Dialects/postgresql.js +286 -0
  212. package/lib/sql-ddl-sync/Dialects/sqlite.d.ts +44 -0
  213. package/lib/sql-ddl-sync/Dialects/sqlite.js +256 -0
  214. package/lib/sql-ddl-sync/SQL.d.ts +12 -0
  215. package/lib/sql-ddl-sync/SQL.js +108 -0
  216. package/lib/sql-ddl-sync/Typo/Collection.d.ts +13 -0
  217. package/lib/sql-ddl-sync/Typo/Collection.js +1 -0
  218. package/lib/sql-ddl-sync/Typo/DbIndex.d.ts +13 -0
  219. package/lib/sql-ddl-sync/Typo/DbIndex.js +1 -0
  220. package/lib/sql-ddl-sync/Typo/Dialect.d.ts +81 -0
  221. package/lib/sql-ddl-sync/Typo/Dialect.js +1 -0
  222. package/lib/sql-ddl-sync/Typo/Driver.d.ts +53 -0
  223. package/lib/sql-ddl-sync/Typo/Driver.js +1 -0
  224. package/lib/sql-ddl-sync/Typo/Query.d.ts +7 -0
  225. package/lib/sql-ddl-sync/Typo/Query.js +1 -0
  226. package/lib/sql-ddl-sync/Typo/SQL.d.ts +31 -0
  227. package/lib/sql-ddl-sync/Typo/SQL.js +1 -0
  228. package/lib/sql-ddl-sync/Typo/_common.d.ts +29 -0
  229. package/lib/sql-ddl-sync/Typo/_common.js +1 -0
  230. package/lib/sql-ddl-sync/Utils.d.ts +40 -0
  231. package/lib/sql-ddl-sync/Utils.js +217 -0
  232. package/lib/sql-ddl-sync/index.d.ts +87 -0
  233. package/lib/sql-ddl-sync/index.js +371 -0
  234. package/lib/sql-query/Comparators.d.ts +3 -0
  235. package/lib/sql-query/Comparators.js +94 -0
  236. package/lib/sql-query/Create.d.ts +35 -0
  237. package/lib/sql-query/Create.js +77 -0
  238. package/lib/sql-query/Dialects/dm.d.ts +3 -0
  239. package/lib/sql-query/Dialects/dm.js +74 -0
  240. package/lib/sql-query/Dialects/index.d.ts +10 -0
  241. package/lib/sql-query/Dialects/index.js +12 -0
  242. package/lib/sql-query/Dialects/mssql.d.ts +3 -0
  243. package/lib/sql-query/Dialects/mssql.js +73 -0
  244. package/lib/sql-query/Dialects/mysql.d.ts +3 -0
  245. package/lib/sql-query/Dialects/mysql.js +100 -0
  246. package/lib/sql-query/Dialects/postgresql.d.ts +3 -0
  247. package/lib/sql-query/Dialects/postgresql.js +76 -0
  248. package/lib/sql-query/Dialects/sqlite.d.ts +3 -0
  249. package/lib/sql-query/Dialects/sqlite.js +61 -0
  250. package/lib/sql-query/Helpers.d.ts +38 -0
  251. package/lib/sql-query/Helpers.js +259 -0
  252. package/lib/sql-query/Insert.d.ts +12 -0
  253. package/lib/sql-query/Insert.js +33 -0
  254. package/lib/sql-query/Query.d.ts +29 -0
  255. package/lib/sql-query/Query.js +119 -0
  256. package/lib/sql-query/Remove.d.ts +16 -0
  257. package/lib/sql-query/Remove.js +93 -0
  258. package/lib/sql-query/Select.d.ts +62 -0
  259. package/lib/sql-query/Select.js +533 -0
  260. package/lib/sql-query/Set.d.ts +4 -0
  261. package/lib/sql-query/Set.js +16 -0
  262. package/lib/sql-query/Typo/Aggregation.d.ts +32 -0
  263. package/lib/sql-query/Typo/Aggregation.js +1 -0
  264. package/lib/sql-query/Typo/Comparators.d.ts +140 -0
  265. package/lib/sql-query/Typo/Comparators.js +1 -0
  266. package/lib/sql-query/Typo/Dialect.d.ts +39 -0
  267. package/lib/sql-query/Typo/Dialect.js +1 -0
  268. package/lib/sql-query/Typo/Field.d.ts +8 -0
  269. package/lib/sql-query/Typo/Field.js +1 -0
  270. package/lib/sql-query/Typo/Helper.d.ts +4 -0
  271. package/lib/sql-query/Typo/Helper.js +1 -0
  272. package/lib/sql-query/Typo/Query-ChainBuilder.d.ts +80 -0
  273. package/lib/sql-query/Typo/Query-ChainBuilder.js +1 -0
  274. package/lib/sql-query/Typo/Query.d.ts +34 -0
  275. package/lib/sql-query/Typo/Query.js +16 -0
  276. package/lib/sql-query/Typo/Sql.d.ts +143 -0
  277. package/lib/sql-query/Typo/Sql.js +1 -0
  278. package/lib/sql-query/Typo/SubQuery.d.ts +39 -0
  279. package/lib/sql-query/Typo/SubQuery.js +1 -0
  280. package/lib/sql-query/Typo/index.d.ts +9 -0
  281. package/lib/sql-query/Typo/index.js +1 -0
  282. package/lib/sql-query/Update.d.ts +15 -0
  283. package/lib/sql-query/Update.js +38 -0
  284. package/lib/sql-query/Where.d.ts +4 -0
  285. package/lib/sql-query/Where.js +280 -0
  286. package/package.json +72 -36
  287. package/.travis.yml +0 -14
  288. package/@types/index.d.ts +0 -254
  289. package/@types/orm_mirror/orm.d.ts +0 -275
  290. package/@types/orm_mirror/sql-query.d.ts +0 -79
  291. package/Readme.md +0 -843
  292. package/lib/index.js +0 -13
  293. package/lib/modules/mysql.js +0 -35
  294. package/lib/modules/sqlite3.js +0 -27
  295. package/lib/patch.js +0 -271
package/Readme.md DELETED
@@ -1,843 +0,0 @@
1
- ## Object Relational Mapping for fibjs
2
-
3
- [![Build Status](https://travis-ci.org/fibjs/fib-orm.svg)](https://travis-ci.org/fibjs/fib-orm)
4
- [![NPM version](https://img.shields.io/npm/v/fib-orm.svg)](https://www.npmjs.org/package/fib-orm)
5
-
6
- ## Install
7
-
8
- ```sh
9
- npm install fib-orm
10
- ```
11
-
12
- ## Test
13
-
14
- ```sh
15
- npm run ci
16
- ```
17
-
18
- ## DBMS Support
19
-
20
- - MySQL & MariaDB
21
- - SQLite
22
-
23
- ## Features
24
-
25
- fib-orm add a set of synchronous version method on node-orm object.
26
-
27
- ## Introduction
28
-
29
- This is a fibjs object relational mapping module.
30
-
31
- An example:
32
-
33
- ```js
34
- var orm = require("fib-orm");
35
-
36
- var db = orm.connectSync("mysql://username:password@host/database");
37
- var Person = db.define("person", {
38
- name : String,
39
- surname : String,
40
- age : Number, // FLOAT
41
- male : Boolean,
42
- continent : [ "Europe", "America", "Asia", "Africa", "Australia", "Antartica" ], // ENUM type
43
- photo : Buffer, // BLOB/BINARY
44
- data : Object // JSON encoded
45
- }, {
46
- methods: {
47
- fullName: function () {
48
- return this.name + ' ' + this.surname;
49
- }
50
- },
51
- validations: {
52
- age: orm.enforce.ranges.number(18, undefined, "under-age")
53
- }
54
- });
55
-
56
- // add the table to the database
57
- db.syncSync();
58
-
59
- // add a row to the person table
60
- Person.createSync({ id: 1, name: "John", surname: "Doe", age: 27 });
61
-
62
- // query the person table by surname
63
- var people = Person.findSync({ surname: "Doe" });
64
- // SQL: "SELECT * FROM person WHERE surname = 'Doe'"
65
-
66
- console.log("People found: %d", people.length);
67
- console.log("First person: %s, age %d", people[0].fullName(), people[0].age);
68
-
69
- people[0].age = 16;
70
- people[0].saveSync();
71
- ```
72
-
73
- The node.js version like this:
74
- ```js
75
- var orm = require("orm");
76
-
77
- orm.connect("mysql://username:password@host/database", function (err, db) {
78
- if (err) throw err;
79
-
80
- var Person = db.define("person", {
81
- name : String,
82
- surname : String,
83
- age : Number, // FLOAT
84
- male : Boolean,
85
- continent : [ "Europe", "America", "Asia", "Africa", "Australia", "Antartica" ], // ENUM type
86
- photo : Buffer, // BLOB/BINARY
87
- data : Object // JSON encoded
88
- }, {
89
- methods: {
90
- fullName: function () {
91
- return this.name + ' ' + this.surname;
92
- }
93
- },
94
- validations: {
95
- age: orm.enforce.ranges.number(18, undefined, "under-age")
96
- }
97
- });
98
-
99
- // add the table to the database
100
- db.sync(function(err) {
101
- if (err) throw err;
102
-
103
- // add a row to the person table
104
- Person.create({ id: 1, name: "John", surname: "Doe", age: 27 }, function(err) {
105
- if (err) throw err;
106
-
107
- // query the person table by surname
108
- Person.find({ surname: "Doe" }, function (err, people) {
109
- // SQL: "SELECT * FROM person WHERE surname = 'Doe'"
110
- if (err) throw err;
111
-
112
- console.log("People found: %d", people.length);
113
- console.log("First person: %s, age %d", people[0].fullName(), people[0].age);
114
-
115
- people[0].age = 16;
116
- people[0].save(function (err) {
117
- // err.msg = "under-age";
118
- });
119
- });
120
-
121
- });
122
- });
123
- });
124
- ```
125
-
126
- ## Documentation
127
-
128
-
129
- Fibjs did not add new functions, the development of documents can refer to node-orm, only need to change the asynchronous call to synchronous version. [wiki](https://github.com/dresende/node-orm2/wiki/).
130
-
131
- ## Settings
132
-
133
- See information in the [wiki](https://github.com/dresende/node-orm2/wiki/Settings).
134
-
135
- ## Connecting
136
-
137
- See information in the [wiki](https://github.com/dresende/node-orm2/wiki/Connecting-to-Database).
138
-
139
- ## Models
140
-
141
- A Model is an abstraction over one or more database tables. Models support associations (more below). The name of the model is assumed to match the table name.
142
-
143
- Models support behaviours for accessing and manipulating table data.
144
-
145
- ## Defining Models
146
-
147
- See information in the [wiki](https://github.com/dresende/node-orm2/wiki/Defining-Models).
148
-
149
- ### Properties
150
-
151
- See information in the [wiki](https://github.com/dresende/node-orm2/wiki/Model-Properties).
152
-
153
- ### Instance Methods
154
-
155
- Are passed in during model definition.
156
-
157
- ```js
158
- var Person = db.define('person', {
159
- name : String,
160
- surname : String
161
- }, {
162
- methods: {
163
- fullName: function () {
164
- return this.name + ' ' + this.surname;
165
- }
166
- }
167
- });
168
-
169
- var person = Person.getSync(4);
170
- console.log( person.fullName() );
171
- ```
172
-
173
- ### Model Methods
174
-
175
- Are defined directly on the model.
176
-
177
- ```js
178
- var Person = db.define('person', {
179
- name : String,
180
- height : { type: 'integer' }
181
- });
182
- Person.tallerThan = function(height) {
183
- return this.findSync({ height: orm.gt(height) });
184
- };
185
-
186
- var tallPeople = Person.tallerThan( 192);
187
- ```
188
-
189
-
190
- ## Loading Models [NOT SUPPORT]
191
-
192
- Models can be in separate modules. Simply ensure that the module holding the models uses module.exports to publish a function that accepts the database connection, then load your models however you like.
193
-
194
- Note - using this technique you can have cascading loads.
195
-
196
- ```js
197
- // your main file (after connecting)
198
- db.loadSync("./models");
199
- // loaded!
200
- var Person = db.models.person;
201
- var Pet = db.models.pet;
202
-
203
- // models.js
204
- module.exports = function (db) {
205
- db.loadSync("./models-extra");
206
- db.define('person', {
207
- name : String
208
- });
209
- };
210
-
211
- // models-extra.js
212
- module.exports = function (db) {
213
- db.define('pet', {
214
- name : String
215
- });
216
- };
217
- ```
218
-
219
- ## Synchronizing Models
220
-
221
- See information in the [wiki](https://github.com/dresende/node-orm2/wiki/Syncing-and-dropping-models).
222
-
223
- ## Dropping Models
224
-
225
- See information in the [wiki](https://github.com/dresende/node-orm2/wiki/Syncing-and-dropping-models).
226
-
227
- ## Advanced Options
228
-
229
- ORM2 allows you some advanced tweaks on your Model definitions. You can configure these via settings or in the call to `define` when you setup the Model.
230
-
231
- For example, each Model instance has a unique ID in the database. This table column is added automatically, and called "id" by default.<br/>
232
- If you define your own `key: true` column, "id" will not be added:
233
-
234
- ```js
235
- var Person = db.define("person", {
236
- personId : { type: 'serial', key: true },
237
- name : String
238
- });
239
-
240
- // You can also change the default "id" property name globally:
241
- db.settings.set("properties.primary_key", "UID");
242
-
243
- // ..and then define your Models
244
- var Pet = db.define("pet", {
245
- name : String
246
- });
247
- ```
248
-
249
- **Pet** model will have 2 columns, an `UID` and a `name`.
250
-
251
- It's also possible to have composite keys:
252
-
253
- ```js
254
- var Person = db.define("person", {
255
- firstname : { type: 'text', key: true },
256
- lastname : { type: 'text', key: true }
257
- });
258
- ```
259
-
260
- Other options:
261
-
262
- - `identityCache` : (default: `false`) Set it to `true` to enable identity cache ([Singletons](#singleton)) or set a timeout value (in seconds);
263
- - `autoSave` : (default: `false`) Set it to `true` to save an Instance right after changing any property;
264
- - `autoFetch` : (default: `false`) Set it to `true` to fetch associations when fetching an instance from the database;
265
- - `autoFetchLimit` : (default: `1`) If `autoFetch` is enabled this defines how many hoops (associations of associations)
266
- you want it to automatically fetch.
267
-
268
- ## Hooks
269
-
270
- See information in the [wiki](https://github.com/dresende/node-orm2/wiki/Model-Hooks).
271
-
272
- ## Finding Items
273
-
274
- ### Model.getSync(id, [ options ])
275
-
276
- To get a specific element from the database use `Model.get`.
277
-
278
- ```js
279
- var person = Person.getSync(123);
280
- // finds person with id = 123
281
- ```
282
-
283
- ### Model.findSync([ conditions ] [, options ] [, limit ] [, order ])
284
-
285
- Finding one or more elements has more options, each one can be given in no specific parameter order. Only `options` has to be after `conditions` (even if it's an empty object).
286
-
287
- ```js
288
- var people = Person.findSync({ name: "John", surname: "Doe" }, 3);
289
- // finds people with name='John' AND surname='Doe' and returns the first 3
290
- ```
291
-
292
- If you need to sort the results because you're limiting or just because you want them sorted do:
293
-
294
- ```js
295
- var people = Person.findSync({ surname: "Doe" }, "name");
296
- // finds people with surname='Doe' and returns sorted by name ascending
297
-
298
- people = Person.findSync({ surname: "Doe" }, [ "name", "Z" ]);
299
- // finds people with surname='Doe' and returns sorted by name descending
300
- // ('Z' means DESC; 'A' means ASC - default)
301
- ```
302
-
303
- There are more options that you can pass to find something. These options are passed in a second object:
304
-
305
- ```js
306
- var people = Person.findSync({ surname: "Doe" }, { offset: 2 });
307
- // finds people with surname='Doe', skips the first 2 and returns the others
308
- ```
309
-
310
- You can also use raw SQL when searching. It's documented in the *Chaining* section below.
311
-
312
- ### Model.countSync([ conditions])
313
-
314
- If you just want to count the number of items that match a condition you can just use `.count()` instead of finding all
315
- of them and counting. This will actually tell the database server to do a count (it won't be done in the node process itself).
316
-
317
- ```js
318
- var count = Person.countSync({ surname: "Doe" });
319
- console.log("We have %d Does in our db", count);
320
- ```
321
-
322
- ### Model.existsSync([ conditions])
323
-
324
- Similar to `.count()`, this method just checks if the count is greater than zero or not.
325
-
326
- ```js
327
- var exists = Person.existsSync({ surname: "Doe" });
328
- console.log("We %s Does in our db", exists ? "have" : "don't have");
329
- ```
330
-
331
- ### Aggregating Functions
332
-
333
-
334
- An `Array` of properties can be passed to select only a few properties. An `Object` is also accepted to define conditions.
335
-
336
- Here's an example to illustrate how to use `.groupBy()`:
337
-
338
- ```js
339
- //The same as "select avg(weight), age from person where country='someCountry' group by age;"
340
- var stats = Person.aggregate(["age"], { country: "someCountry" }).avg("weight").groupBy("age").getSync();
341
- // stats is an Array, each item should have 'age' and 'avg_weight'
342
- ```
343
-
344
- ### Base `.aggregate()` methods
345
-
346
- - `.limit()`: you can pass a number as a limit, or two numbers as offset and limit respectively
347
- - `.order()`: same as `Model.find().order()`
348
-
349
- ### Additional `.aggregate()` methods
350
-
351
- - `min`
352
- - `max`
353
- - `avg`
354
- - `sum`
355
- - `count` (there's a shortcut to this - `Model.count`)
356
-
357
- There are more aggregate functions depending on the driver (Math functions for example).
358
-
359
- ### Chaining
360
-
361
- If you prefer less complicated syntax you can chain `.find()` by not giving a callback parameter.
362
-
363
- ```js
364
- var people = Person.find({ surname: "Doe" }).limit(3).offset(2).only("name", "surname").runSync();
365
- // finds people with surname='Doe', skips first 2 and limits to 3 elements,
366
- // returning only 'name' and 'surname' properties
367
- ```
368
- If you want to skip just one or two properties, you can call `.omit()` instead of `.only`.
369
-
370
- Chaining allows for more complicated queries. For example, we can search by specifying custom SQL:
371
- ```js
372
- Person.find({ age: 18 }).where("LOWER(surname) LIKE ?", ['dea%']).allSync( ... );
373
- ```
374
- It's bad practice to manually escape SQL parameters as it's error prone and exposes your application to SQL injection.
375
- The `?` syntax takes care of escaping for you, by safely substituting the question mark in the query with the parameters provided.
376
- You can also chain multiple `where` clauses as needed.
377
-
378
- `.find`, `.where` & `.all` do the same thing; they are all interchangeable and chainable.
379
-
380
- You can also `order` or `orderRaw`:
381
- ```js
382
- Person.find({ age: 18 }).order('-name').allSync( ... );
383
- // see the 'Raw queries' section below for more details
384
- Person.find({ age: 18 }).orderRaw("?? DESC", ['age']).allSync( ... );
385
- ```
386
-
387
- You can also chain and just get the count in the end. In this case, offset, limit and order are ignored.
388
-
389
- ```js
390
- var people = Person.find({ surname: "Doe" }).countSync();
391
- // people = number of people with surname="Doe"
392
- ```
393
-
394
- Also available is the option to remove the selected items.
395
- Note that a chained remove will not run any hooks.
396
-
397
- ```js
398
- Person.find({ surname: "Doe" }).removeSync();
399
- // Does gone..
400
- ```
401
-
402
- You can also make modifications to your instances using common Array traversal methods and save everything
403
- in the end. [NOT SUPPORT]
404
-
405
- ```js
406
- Person.find({ surname: "Doe" }).each(function (person) {
407
- person.surname = "Dean";
408
- }).save(function (err) {
409
- // done!
410
- });
411
-
412
- Person.find({ surname: "Doe" }).each().filter(function (person) {
413
- return person.age >= 18;
414
- }).sort(function (person1, person2) {
415
- return person1.age < person2.age;
416
- }).get(function (people) {
417
- // get all people with at least 18 years, sorted by age
418
- });
419
- ```
420
-
421
- Of course you could do this directly on `.find()`, but for some more complicated tasks this can be very usefull.
422
-
423
- `Model.find()` does not return an Array so you can't just chain directly. To start chaining you have to call
424
- `.each()` (with an optional callback if you want to traverse the list). You can then use the common functions
425
- `.filter()`, `.sort()` and `.forEach()` more than once.
426
-
427
- In the end (or during the process..) you can call:
428
- - `.countSync()` if you just want to know how many items there are;
429
- - `.getSync()` to retrieve the list;
430
- - `.saveSync()` to save all item changes.
431
-
432
- #### Conditions
433
-
434
- Conditions are defined as an object where every key is a property (table column). All keys are supposed
435
- to be concatenated by the logical `AND`. Values are considered to match exactly, unless you're passing
436
- an `Array`. In this case it is considered a list to compare the property with.
437
-
438
- ```js
439
- { col1: 123, col2: "foo" } // `col1` = 123 AND `col2` = 'foo'
440
- { col1: [ 1, 3, 5 ] } // `col1` IN (1, 3, 5)
441
- ```
442
-
443
- If you need other comparisons, you have to use a special object created by some helper functions. Here are
444
- a few examples to describe it:
445
-
446
- ```js
447
- { col1: orm.eq(123) } // `col1` = 123 (default)
448
- { col1: orm.ne(123) } // `col1` <> 123
449
- { col1: orm.gt(123) } // `col1` > 123
450
- { col1: orm.gte(123) } // `col1` >= 123
451
- { col1: orm.lt(123) } // `col1` < 123
452
- { col1: orm.lte(123) } // `col1` <= 123
453
- { col1: orm.between(123, 456) } // `col1` BETWEEN 123 AND 456
454
- { col1: orm.not_between(123, 456) } // `col1` NOT BETWEEN 123 AND 456
455
- { col1: orm.like(12 + "%") } // `col1` LIKE '12%'
456
- { col1: orm.not_like(12 + "%") } // `col1` NOT LIKE '12%'
457
- { col1: orm.not_in([1, 4, 8]) } // `col1` NOT IN (1, 4, 8)
458
- ```
459
-
460
- #### Raw queries
461
-
462
- ```js
463
- var data = db.driver.execQuerySync("SELECT id, email FROM user")
464
-
465
- // You can escape identifiers and values.
466
- // For identifier substitution use: ??
467
- // For value substitution use: ?
468
- var data = db.driver.execQuerySync(
469
- "SELECT user.??, user.?? FROM user WHERE user.?? LIKE ? AND user.?? > ?",
470
- ['id', 'name', 'name', 'john', 'id', 55])
471
-
472
- // Identifiers don't need to be scaped most of the time
473
- var data = db.driver.execQuerySync(
474
- "SELECT user.id, user.name FROM user WHERE user.name LIKE ? AND user.id > ?",
475
- ['john', 55])
476
- ```
477
-
478
- ### Identity pattern
479
-
480
- You can use the identity pattern (turned off by default). If enabled, multiple different queries will result in the same result - you will
481
- get the same object. If you have other systems that can change your database or you need to call some manual SQL queries,
482
- you shouldn't use this feature. It is also know to cause some problems with complex
483
- autofetch relationships. Use at your own risk.
484
-
485
- It can be enabled/disabled per model:
486
-
487
- ```js
488
- var Person = db.define('person', {
489
- name : String
490
- }, {
491
- identityCache : true
492
- });
493
- ```
494
-
495
- and also globally:
496
-
497
- ```js
498
- var db = orm.connectSync('...');
499
- db.settings.set('instance.identityCache', true);
500
- ```
501
-
502
- The identity cache can be configured to expire after a period of time by passing in a number instead of a
503
- boolean. The number will be considered the cache timeout in seconds (you can use floating point).
504
-
505
- **Note**: One exception about Caching is that it won't be used if an instance is not saved. For example, if
506
- you fetch a Person and then change it, while it doesn't get saved it won't be passed from Cache.
507
-
508
- ## Creating Items
509
-
510
- ### Model.createSync(items)
511
-
512
- To insert new elements to the database use `Model.create`.
513
-
514
- ```js
515
- var items = Person.createSync([
516
- {
517
- name: "John",
518
- surname: "Doe",
519
- age: 25,
520
- male: true
521
- },
522
- {
523
- name: "Liza",
524
- surname: "Kollan",
525
- age: 19,
526
- male: false
527
- }
528
- ]);
529
- // items - array of inserted items
530
- ```
531
-
532
- ## Updating Items
533
-
534
- Every item returned has the properties that were defined to the Model and also a couple of methods you can
535
- use to change each item.
536
-
537
- ```js
538
- var John = Person.getSync(1);
539
- John.name = "Joe";
540
- John.surname = "Doe";
541
- John.saveSync();
542
- console.log("saved!");
543
- ```
544
-
545
- Updating and then saving an instance can be done in a single call:
546
-
547
- ```js
548
- var John = Person.getSync(1);
549
- John.saveSync({ name: "Joe", surname: "Doe" });
550
- console.log("saved!");
551
- ```
552
-
553
- If you want to remove an instance, just do:
554
-
555
- ```js
556
- // you could do this without even fetching it, look at Chaining section above
557
- var John = Person.getSync(1);
558
- John.removeSync();
559
- console.log("removed!");
560
- ```
561
-
562
- ## Validations
563
-
564
- See information in the [wiki](https://github.com/dresende/node-orm2/wiki/Model-Validations).
565
-
566
- ## Associations
567
-
568
- An association is a relation between one or more tables.
569
-
570
- ### hasOne
571
-
572
- Is a **many to one** relationship. It's the same as **belongs to.**<br/>
573
- Eg: `Animal.hasOne('owner', Person)`.<br/>
574
- Animal can only have one owner, but Person can have many animals.<br/>
575
- Animal will have the `owner_id` property automatically added.
576
-
577
- The following functions will become available:
578
- ```js
579
- animal.getOwnerSync() // Gets owner
580
- animal.setOwnerSync(person) // Sets owner_id
581
- animal.hasOwnerSync() // Checks if owner exists
582
- animal.removeOwnerSync() // Sets owner_id to 0
583
- ```
584
-
585
- **Chain Find**
586
-
587
- The hasOne association is also chain find compatible. Using the example above, we can do this to access a new instance of a ChainFind object:
588
-
589
- ```js
590
- Animal.findByOwner({ /* options */ })
591
- ```
592
-
593
- **Reverse access**
594
-
595
- ```js
596
- Animal.hasOne('owner', Person, {reverse: 'pets'})
597
- ```
598
-
599
- will add the following:
600
-
601
- ```js
602
- // Instance methods
603
- person.getPetsSync(function..)
604
- person.setPetsSync(cat, function..)
605
-
606
- // Model methods
607
- Person.findByPets({ /* options */ }) // returns ChainFind object
608
- ```
609
-
610
- ### hasMany
611
-
612
- Is a **many to many** relationship (includes join table).<br/>
613
- Eg: `Patient.hasMany('doctors', Doctor, { why: String }, { reverse: 'patients', key: true })`.<br/>
614
- Patient can have many different doctors. Each doctor can have many different patients.
615
-
616
- This will create a join table `patient_doctors` when you call `Patient.sync()`:
617
-
618
- column name | type
619
- :-----------|:--------
620
- patient_id | Integer (composite key)
621
- doctor_id | Integer (composite key)
622
- why | varchar(255)
623
-
624
- The following functions will be available:
625
-
626
- ```js
627
- patient.getDoctorsSync() // List of doctors
628
- patient.addDoctorsSync(docs) // Adds entries to join table
629
- patient.setDoctorsSync(docs) // Removes existing entries in join table, adds new ones
630
- patient.hasDoctorsSync(docs) // Checks if patient is associated to specified doctors
631
- patient.removeDoctorsSync(docs) // Removes specified doctors from join table
632
-
633
- doctor.getPatientsSync()
634
- etc...
635
-
636
- // You can also do:
637
- patient.doctors = [doc1, doc2];
638
- patient.saveSync()
639
- ```
640
-
641
- To associate a doctor to a patient:
642
-
643
- ```js
644
- patient.addDoctorSync(surgeon, {why: "remove appendix"})
645
- ```
646
-
647
- which will add `{patient_id: 4, doctor_id: 6, why: "remove appendix"}` to the join table.
648
-
649
- #### getAccessor
650
-
651
- This accessor in this type of association returns a `ChainFind` if not passing a callback. This means you can
652
- do things like:
653
-
654
- ```js
655
- var doctors = patient.getDoctors().order("name").offset(1).runSync());
656
- // ... all doctors, ordered by name, excluding first one
657
- ```
658
-
659
- ### extendsTo
660
-
661
- If you want to split maybe optional properties into different tables or collections. Every extension will be in a new table,
662
- where the unique identifier of each row is the main model instance id. For example:
663
-
664
- ```js
665
- var Person = db.define("person", {
666
- name : String
667
- });
668
- var PersonAddress = Person.extendsTo("address", {
669
- street : String,
670
- number : Number
671
- });
672
- ```
673
-
674
- This will create a table `person` with columns `id` and `name`. The extension will create a table `person_address` with
675
- columns `person_id`, `street` and `number`. The methods available in the `Person` model are similar to an `hasOne`
676
- association. In this example you would be able to call `.getAddress(cb)`, `.setAddress(Address, cb)`, ..
677
-
678
- **Note:** you don't have to save the result from `Person.extendsTo`. It returns an extended model. You can use it to query
679
- directly this extended table (and even find the related model) but that's up to you. If you only want to access it using the
680
- original model you can just discard the return.
681
-
682
- ### Examples & options
683
-
684
- If you have a relation of 1 to n, you should use `hasOne` (belongs to) association.
685
-
686
- ```js
687
- var Person = db.define('person', {
688
- name : String
689
- });
690
- var Animal = db.define('animal', {
691
- name : String
692
- });
693
- Animal.hasOne("owner", Person); // creates column 'owner_id' in 'animal' table
694
-
695
- // get animal with id = 123
696
- var animal = Animal.getSync(123);
697
- // animal is the animal model instance, if found
698
- var person = animal.getOwnerSync();
699
- // if animal has really an owner, person points to it
700
- ```
701
-
702
- You can mark the `owner_id` field as required in the database by specifying the `required` option:
703
- ```js
704
- Animal.hasOne("owner", Person, { required: true });
705
- ```
706
-
707
- If a field is not required, but should be validated even if it is not present, then specify the `alwaysValidate` option.
708
- (this can happen, for example when validation of a null field depends on other fields in the record)
709
- ```js
710
- Animal.hasOne("owner", Person, { required: false, alwaysValidate: true });
711
- ```
712
-
713
- If you prefer to use another name for the field (owner_id) you can change this parameter in the settings.
714
-
715
- ```js
716
- db.settings.set("properties.association_key", "{field}_{name}"); // {name} will be replaced by 'owner' and {field} will be replaced by 'id' in this case
717
- ```
718
-
719
- **Note: This has to be done before the association is specified.**
720
-
721
- The `hasMany` associations can have additional properties in the association table.
722
-
723
- ```js
724
- var Person = db.define('person', {
725
- name : String
726
- });
727
- Person.hasMany("friends", {
728
- rate : Number
729
- }, {}, { key: true });
730
-
731
- var John = Person.getSync(123);
732
- var friends = John.getFriendsSync();
733
- // assumes rate is another column on table person_friends
734
- // you can access it by going to friends[N].extra.rate
735
- ```
736
-
737
- If you prefer you can activate `autoFetch`.
738
- This way associations are automatically fetched when you get or find instances of a model.
739
-
740
- ```js
741
- var Person = db.define('person', {
742
- name : String
743
- });
744
- Person.hasMany("friends", {
745
- rate : Number
746
- }, {
747
- key : true, // Turns the foreign keys in the join table into a composite key
748
- autoFetch : true
749
- });
750
-
751
- var John = Person.getSync(123);
752
- // no need to do John.getFriends() , John already has John.friends Array
753
- ```
754
-
755
- You can also define this option globally instead of a per association basis.
756
-
757
- ```js
758
- var Person = db.define('person', {
759
- name : String
760
- }, {
761
- autoFetch : true
762
- });
763
- Person.hasMany("friends", {
764
- rate : Number
765
- }, {
766
- key: true
767
- });
768
- ```
769
-
770
- Associations can make calls to the associated Model by using the `reverse` option. For example, if you have an
771
- association from ModelA to ModelB, you can create an accessor in ModelB to get instances from ModelA.
772
- Confusing? Look at the next example.
773
-
774
- ```js
775
- var Pet = db.define('pet', {
776
- name : String
777
- });
778
- var Person = db.define('person', {
779
- name : String
780
- });
781
- Pet.hasOne("owner", Person, {
782
- reverse : "pets"
783
- });
784
-
785
- var pets = Person(4).getPetsSync();
786
- // although the association was made on Pet,
787
- // Person will have an accessor (getPets)
788
- //
789
- // In this example, ORM will fetch all pets
790
- // whose owner_id = 4
791
- ```
792
-
793
- This makes even more sense when having `hasMany` associations since you can manage the *many to many*
794
- associations from both sides.
795
-
796
- ```js
797
- var Pet = db.define('pet', {
798
- name : String
799
- });
800
- var Person = db.define('person', {
801
- name : String
802
- });
803
- Person.hasMany("pets", Pet, {
804
- bought : Date
805
- }, {
806
- key : true,
807
- reverse : "owners"
808
- });
809
-
810
- Person(1).getPetsSync(...);
811
- Pet(2).getOwnersSync(...);
812
- ```
813
-
814
-
815
- ## Transaction support
816
-
817
- You can use low level transaction function to process db transcation.
818
- ```js
819
- db.begin();
820
- ...
821
- if(err)
822
- db.rollback();
823
- else
824
- db.commit();
825
- ```
826
- Or you can use trans to simpile process it.
827
- ```js
828
- var result = db.trans(() => {
829
- ...
830
- return result;
831
- });
832
- ```
833
-
834
- ## Adding external database adapters
835
-
836
- To add an external database adapter to `orm`, call the `addAdapter` method, passing in the alias to use for connecting
837
- with this adapter, along with the constructor for the adapter:
838
-
839
- ```js
840
- require('orm').addAdapter('cassandra', CassandraAdapter);
841
- ```
842
-
843
- See [the documentation for creating adapters](./Adapters.md) for more details.