forked from C2FO/patio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.html
1046 lines (863 loc) · 43.9 KB
/
models.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>patio</title>
<link rel="stylesheet" href="./assets/css/bootstrap.css">
<link rel="stylesheet" href="./assets/css/prettify.css">
<style type="text/css">
/*.subnav-inner {*/
/*width: 100%;*/
/*height: 36px;*/
/*background-color: #EEE;*/
/*background-repeat: repeat-x;*/
/*background-image: -moz-linear-gradient(top, whiteSmoke 0%, #EEE 100%);*/
/*background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, whiteSmoke), color-stop(100%, #EEE));*/
/*background-image: -webkit-linear-gradient(top, whiteSmoke 0%, #EEE 100%);*/
/*background-image: -ms-linear-gradient(top, whiteSmoke 0%, #EEE 100%);*/
/*background-image: -o-linear-gradient(top, whiteSmoke 0%, #EEE 100%);*/
/*filter: progid:DXImageTransform.Microsoft.gradient(startColorstr = '#f5f5f5', endColorstr = '#eeeeee', GradientType = 0);*/
/*background-image: linear-gradient(top, whiteSmoke 0%, #EEE 100%);*/
/*-webkit-border-radius: 4px;*/
/*-moz-border-radius: 4px;*/
/*border-radius: 4px;*/
/*}*/
/*.subnav .nav > li > a:hover {*/
/*color: black !important;*/
/*}*/
/*.subnav .nav li.dropdown .dropdown-toggle .caret,*/
/*.subnav .nav li.dropdown.open .caret {*/
/*border-top-color: #999 !important;*/
/*border-bottom-color: #999 !important;*/
/*}*/
/*.subnav-fixed {*/
/*position: fixed;*/
/*width : 90%;*/
/*margin-right: auto;*/
/*margin-left: auto;*/
/*top: 40px;*/
/*left: 0;*/
/*right: 0;*/
/*z-index: 1020;*/
/*border-color: #D5D5D5;*/
/*border-width: 0 0 1px;*/
/*-webkit-border-radius: 0;*/
/*-moz-border-radius: 0;*/
/*border-radius: 0;*/
/*-webkit-box-shadow: inset 0 1px 0 #fff, 0 1px 5px rgba(0,0,0,.1);*/
/*-moz-box-shadow: inset 0 1px 0 #fff, 0 1px 5px rgba(0,0,0,.1);*/
/*box-shadow: inset 0 1px 0 #fff, 0 1px 5px rgba(0,0,0,.1);*/
/*filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);*/
/*}*/
/*.navbar .nav .dropdown-menu {*/
/*max-height: 500px;*/
/*overflow: auto;*/
/*}*/
</style>
<style type="text/css">
body {
padding: 90px;
}
.subnav{
margin-top: 40px;
margin-right: auto;
margin-left: auto;
z-index: 1000;
}
@media (max-width:979px) {
.subnav{
margin-top: auto;
}
}
</style>
<link rel="stylesheet" href="./assets/css/bootstrap-responsive.css">
<script type="text/javascript">
var init = (function () {
"use strict";
var processScroll = (function () {
var curr = null, prev = null;
return function (nav) {
var $win = $(window);
$('.subnav').each(function () {
var nav = $(this);
var navTop = $win.width() < 980 ? 0 : nav.offset().top - 40;
var scrollTop = $win.scrollTop();
if (scrollTop >= navTop && curr != nav) {
if(curr){
curr.removeClass('subnav-fixed')
prev = curr;
}
curr = nav;
curr.addClass('subnav-fixed')
} else if (curr == nav && scrollTop <= navTop) {
curr.removeClass('subnav-fixed');
prev.addClass('subnav-fixed');
curr = prev;
}else{
nav.removeClass('subnav-fixed');
}
});
};
})();
return function () {
window.prettyPrint && prettyPrint();
$(".collapse").collapse();
var $window = $(window);
//$(".subnav").affix ();
// fix sub nav on scroll
// processScroll();
// $(window).on('scroll', processScroll)
}
})();
</script>
</head>
<body onload="init()">
<div class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"> </span>
</a>
<a href="./index.html" class="brand">patio</a>
<div class="nav-collapse">
<ul class="nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Docs<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="./connecting.html">Connecting</a></li>
<li><a href="./models.html">Models</a></li>
<li><a href="./associations.html">Associations</a></li>
<li><a href="./model-inheritance.html">Model Inheritance</a></li>
<li><a href="./validation.html">Model Validation</a></li>
<li><a href="./plugins.html">Model Plugins</a></li>
<li><a href="./querying.html">Querying</a></li>
<li><a href="./DDL.html">DDL</a></li>
<li><a href="./migrations.html">Migrations</a></li>
<li><a href="./logging.html">Logging</a></li>
<li><a href="./coverage.html">Test Coverage</a></li>
</ul>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Namespaces<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="patio_sql.html">patio.sql</a></li>
<li><a href="patio_sql_Constants.html">patio.sql.Constants</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="./patio.html">patio</a></li>
<li><a href="./patio_AlterTableGenerator.html">patio.AlterTableGenerator</a></li>
<li><a href="./patio_AssociationError.html">patio.AssociationError</a></li>
<li><a href="./patio_ConnectionPool.html">patio.ConnectionPool</a></li>
<li><a href="./patio_Database.html">patio.Database</a></li>
<li><a href="./patio_DatabaseError.html">patio.DatabaseError</a></li>
<li><a href="./patio_Dataset.html">patio.Dataset</a></li>
<li><a href="./patio_DatasetError.html">patio.DatasetError</a></li>
<li><a href="./patio_ExpressionError.html">patio.ExpressionError</a></li>
<li><a href="./patio_MigrationError.html">patio.MigrationError</a></li>
<li><a href="./patio_Model.html">patio.Model</a></li>
<li><a href="./patio_ModelError.html">patio.ModelError</a></li>
<li><a href="./patio_NotImplemented.html">patio.NotImplemented</a></li>
<li><a href="./patio_PatioError.html">patio.PatioError</a></li>
<li><a href="./patio_QueryError.html">patio.QueryError</a></li>
<li><a href="./patio_SchemaGenerator.html">patio.SchemaGenerator</a></li>
<li><a href="./patio_Time.html">patio.Time</a></li>
<li><a href="./patio_associations_Association.html">patio.associations.Association</a></li>
<li><a href="./patio_associations_ManyToMany.html">patio.associations.ManyToMany</a></li>
<li><a href="./patio_associations_ManyToOne.html">patio.associations.ManyToOne</a></li>
<li><a href="./patio_associations_ManyToOne.html">patio.associations.ManyToOne</a></li>
<li><a href="./patio_associations_OneToMany.html">patio.associations.OneToMany</a></li>
<li><a href="./patio_dataset.html#._Query">patio.dataset._Query</a></li>
<li><a href="./patio_migrations_IntegerMigrator.html">patio.migrations.IntegerMigrator</a></li>
<li><a href="./patio_migrations_Migrator.html">patio.migrations.Migrator</a></li>
<li><a href="./patio_migrations_TimestampMigrator.html">patio.migrations.TimestampMigrator</a></li>
<li><a href="./patio_plugins_CachePlugin.html">patio.plugins.CachePlugin</a></li>
<li><a href="./patio_plugins_ClassTableInheritancePlugin.html">patio.plugins.ClassTableInheritancePlugin</a></li>
<li><a href="./patio_plugins_ColumnMapper.html">patio.plugins.ColumnMapper</a></li>
<li><a href="./patio_plugins_TimeStampPlugin.html">patio.plugins.TimeStampPlugin</a></li>
<li><a href="./patio_plugins_ValidatorPlugin.html">patio.plugins.ValidatorPlugin</a></li>
<li><a href="./patio_sql_AliasMethods.html">patio.sql.AliasMethods</a></li>
<li><a href="./patio_sql_AliasedExpression.html">patio.sql.AliasedExpression</a></li>
<li><a href="./patio_sql_BitWiseMethods.html">patio.sql.BitWiseMethods</a></li>
<li><a href="./patio_sql_BooleanConstant.html">patio.sql.BooleanConstant</a></li>
<li><a href="./patio_sql_BooleanExpression.html">patio.sql.BooleanExpression</a></li>
<li><a href="./patio_sql_BooleanMethods.html">patio.sql.BooleanMethods</a></li>
<li><a href="./patio_sql_CaseExpression.html">patio.sql.CaseExpression</a></li>
<li><a href="./patio_sql_Cast.html#.constructor">patio.sql.Cast.constructor</a></li>
<li><a href="./patio_sql_CastMethods.html">patio.sql.CastMethods</a></li>
<li><a href="./patio_sql_ColumnAll.html">patio.sql.ColumnAll</a></li>
<li><a href="./patio_sql_ComplexExpression.html">patio.sql.ComplexExpression</a></li>
<li><a href="./patio_sql_ComplexExpressionMethods.html">patio.sql.ComplexExpressionMethods</a></li>
<li><a href="./patio_sql_Constant.html">patio.sql.Constant</a></li>
<li><a href="./patio_sql_DateTime.html">patio.sql.DateTime</a></li>
<li><a href="./patio_sql_Decimal.html">patio.sql.Decimal</a></li>
<li><a href="./patio_sql_Expression.html">patio.sql.Expression</a></li>
<li><a href="./patio_sql_Float.html">patio.sql.Float</a></li>
<li><a href="./patio_sql_GenericExpression.html">patio.sql.GenericExpression</a></li>
<li><a href="./patio_sql_Identifier.html">patio.sql.Identifier</a></li>
<li><a href="./patio_sql_InequalityMethods.html">patio.sql.InequalityMethods</a></li>
<li><a href="./patio_sql_JoinClause.html">patio.sql.JoinClause</a></li>
<li><a href="./patio_sql_JoinOnClause.html">patio.sql.JoinOnClause</a></li>
<li><a href="./patio_sql_JoinUsingClause.html">patio.sql.JoinUsingClause</a></li>
<li><a href="./patio_sql_LiteralString.html#.constructor">patio.sql.LiteralString.constructor</a></li>
<li><a href="./patio_sql_NoBooleanInputMethods.html">patio.sql.NoBooleanInputMethods</a></li>
<li><a href="./patio_sql_NumericExpression.html">patio.sql.NumericExpression</a></li>
<li><a href="./patio_sql_NumericMethods.html">patio.sql.NumericMethods</a></li>
<li><a href="./patio_sql_OrderedExpression.html">patio.sql.OrderedExpression</a></li>
<li><a href="./patio_sql_OrderedMethods.html">patio.sql.OrderedMethods</a></li>
<li><a href="./patio_sql_PlaceHolderLiteralString.html">patio.sql.PlaceHolderLiteralString</a></li>
<li><a href="./patio_sql_QualifiedIdentifier.html">patio.sql.QualifiedIdentifier</a></li>
<li><a href="./patio_sql_QualifyingMethods.html">patio.sql.QualifyingMethods</a></li>
<li><a href="./patio_sql_SQLFunction.html">patio.sql.SQLFunction</a></li>
<li><a href="./patio_sql_StringConcatenationMethods.html">patio.sql.StringConcatenationMethods</a></li>
<li><a href="./patio_sql_StringExpression.html">patio.sql.StringExpression</a></li>
<li><a href="./patio_sql_StringMethods.html">patio.sql.StringMethods</a></li>
<li><a href="./patio_sql_SubScript.html">patio.sql.SubScript</a></li>
<li><a href="./patio_sql_SubscriptMethods.html">patio.sql.SubscriptMethods</a></li>
<li><a href="./patio_sql_Time.html">patio.sql.Time</a></li>
<li><a href="./patio_sql_TimeStamp.html">patio.sql.TimeStamp</a></li>
<li><a href="./patio_sql_Year.html">patio.sql.Year</a></li>
</ul>
</li>
</ul>
<ul class="nav pull-right">
<li class="divider-vertical"></li>
<li><a href="https://github.com/Pollenware/patio" target="#github" class="pull-right">github</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<a name="top"></a>
<div class="container">
<h1>Models</h1>
<p>Models are an optional feature in patio that can be extended to encapsulate, query, and associate tables.
</p>
<p>When defining a model it is assumed that the database table already exists. So before defining a model you must create the table/s that the model requires to function including associations. To create a model you must <a href="./patio.html#connect">connect</a> to a database.
</p>
<p>An example model definition flow.
</p>
<pre class='prettyprint linenums lang-js'><code>var comb = require("comb"),
format = comb.string.format,
patio = require("patio");
patio.camelize = true;
//if you want logging
patio.configureLogging();
//disconnect and error callback helpers
var disconnect = patio.disconnect.bind(patio);
var disconnectError = function(err) {
patio.logError(err);
patio.disconnect();
};
//create your DB
var DB = patio.connect("mysql://test:testpass@localhost:3306/sandbox");
//create an initial model. It cannot be used until it is synced.
//To sync call User.sync or patio.syncModels is called
var User = patio.addModel("user");
var createSchema = function(){
return DB.forceCreateTable("user", function(){
this.primaryKey("id");
this.firstName(String)
this.lastName(String);
this.password(String);
this.dateOfBirth(Date);
this.created(sql.TimeStamp);
this.updated(sql.DateTime);
});
};
//connect and create schema
connectAndCreateSchema()
.then(function(){
//sync the model so it can be used
patio.syncModels().then(function(){
var myUser = new User({
firstName : "Bob",
lastName : "Yukon",
password : "password",
dateOfBirth : new Date(1980, 8, 29)
});
//save the user
myUser.save().then(function(user){
console.log(format("%s %s's id is %d", user.firstName, user.lastName, user.id));
disconnect();
}, disconnectError);
}, disconnectError);
}, disconnectError);</code></pre>
<p>The flow for the above example is as follows:
</p>
<ul>
<li>Connects to a database and creates the "user" table.</li></li>
<li>Sync the models. This gets the relevant table information from the "user" table</li>
<li>Create a new User<ul>
<li>Save the user</li>
<li>Print out some user details, at this point the user is saved in the database</li>
<li>disconnect from the database</li>
</ul>
</li>
<li>The final output should be "BobYukon's id is 1".</li>
</ul>
<h2>Options</h2>
<p>Models some options that allow for the customization of the way a model be haves when interacting
with the database.
</p>
<ul>
<li><strong>typecastOnLoad</strong> : Defaults to true. Set to false to prevent properties from being type casted when loaded from the database. See <a href="./patio_Database.html#typecastValue">patio.Database.typecastValue</a></li>
</ul>
<pre class='prettyprint linenums lang-js'><code>patio.addModel("user", {
static : {
//override default
typecastOnLoad : false
}
});</code></pre>
<ul>
<li><strong>typecastOnAssignment</strong> : Defaults to true. Set to false to prevent properties from being type casted when set by something other than the return values from the database. See <a href="./patio_Database.html#typecastValue">patio.Database.typecastValue</a></li>
</ul>
<pre class='prettyprint linenums lang-js'><code>patio.addModel("user", {
static : {
//override default
typecastOnAssignment : false
}
});</code></pre>
<p>So the following would not be typecasted.
</p>
<pre class='prettyprint linenums lang-js'><code>var myUser = new User();
myUser.updated = new Date(2004, 1, 1, 12, 12, 12); //would not be auto converted to a patio.sql.DateTime
myUser.updated = "2004-02-01 12:12:12" //would not be auto converted to a patio.sql.DateTime</code></pre>
<ul>
<li><strong>typecastEmptyStringToNull</strong> : Defaults to true. Set to false to prevent empty strings from being typecasted to null.</li>
</ul>
<pre class='prettyprint linenums lang-js'><code>patio.addModel("user", {
static : {
//override default
typecastEmptyStringToNull : false
}
});</code></pre>
<ul>
<li><strong>raiseOnTypecastError</strong> : Defaults to true. Set to false to prevent errors thrown while type casting a value from being propogated. <strong>USE WITH CARE</strong></li>
</ul>
<pre class='prettyprint linenums lang-js'><code>patio.addModel("user", {
static : {
//override default
raiseOnTypecastError : false
}
});</code></pre>
<ul>
<li><strong>useTransactions</strong> : Defaults to true. Set to false to prevent models from using transactions when saving, deleting, or updating. This applies to the model associations also.</li>
</ul>
<pre class='prettyprint linenums lang-js'><code>patio.addModel("user", {
static : {
//override default
useTransactions : false
}
});</code></pre>
<ul>
<li><strong>identifierOutputMethod</strong> : Defaults to null. Set this to override the Dataset default method of converting identifiers returned from the database. See <a href="./patio_Dataset.html#.identifierOutputMethod">patio.Dataset.identifierOutputMethod</a> </li>
</ul>
<pre class='prettyprint linenums lang-js'><code>patio.addModel("user", {
static : {
//override default
identifierOutputMethod : "camelize"
}
});</code></pre>
<ul>
<li><strong>identifierInputMethod</strong> : Defaults to null. Set this to override the Dataset default method of converting identifiers when sending them to the database. See <a href="./patio_Dataset.html#.identifierInputMethod">patio.Dataset.identifierInputMethod</a>.</li>
</ul>
<pre class='prettyprint linenums lang-js'><code>patio.addModel("user", {
static : {
//override default
identifierInputMethod : "underscore"
}
});</code></pre>
<ul>
<li><strong>camelize</strong> : Defaults to null. Set this to true force this particular model's identifiers to be underscored when sent to the database and camelized when returned. This <strong>WILL</strong> override <code>patio.camelize</code>. <strong>USE WITH CARE</strong></li>
</ul>
<pre class='prettyprint linenums lang-js'><code>patio.addModel("user", {
static : {
//override default
camelize : true
}
});</code></pre>
<ul>
<li><strong>underscore</strong> : Defaults to null. Set this to force this particular model's identifiers to be camelized when sent to the database and underscored when returned. This <strong>WILL</strong> override <code>patio.underscore</code>. <strong>USE WITH CARE</strong></li>
</ul>
<pre class='prettyprint linenums lang-js'><code>patio.addModel("user", {
static : {
//override default
underscore : true
}
});</code></pre>
<ul>
<li><strong>reloadOnSave</strong> : Defaults to true. Set this to false to prevent the models properties from being reloaded from the database after a save operation. <strong>Note</strong>: If you set this to false and you have columns that have default values in the database and they are not explictly set they will <strong>NOT</strong> be loaded</li>
</ul>
<pre class='prettyprint linenums lang-js'><code>patio.addModel("user", {
static : {
//override default
reloadOnSave : false
}
});</code></pre>
<ul>
<li><strong>reloadOnUpdate</strong> : Defaults to true. Set this to false to prevent the model's properties from being reloaded from the database when a model is updated. <strong>Note</strong>: If you set this to false and you have columns that have default values in the database and they are not explictly set they will <strong>NOT</strong> be refreshed.</li>
</ul>
<pre class='prettyprint linenums lang-js'><code>patio.addModel("user", {
static : {
//override default
reloadOnUpdate : false
}
});</code></pre>
<h2>Creating a model</h2>
<p>To create a Model class to use within your code you use the <a href=".patio.html#addModel">patio.addModel</a> method.
</p>
<pre class='prettyprint linenums lang-js'><code>var User = patio.addModel("user")
//you must sync the model before using it
User.sync().then(function(User){
var myUser = new User({
firstName : "Bob",
lastName : "Yukon",
password : "password",
dateOfBirth : new Date(1980, 8, 29)
});
myUser.save().then(function(){
console.log(format("%s %s was created at %s", myUser.firstName, myUser.lastName, myUser.created.toString()));
console.log(format("%s %s's id is %d", myUser.firstName, myUser.lastName, myUser.id));
}, disconnectError);
});</code></pre>
<p>You may also use a dataset when adding a model. You might use this if you are using multiple databases. Or want to use a custom query as the base for a particular model.
</p>
<pre class='prettyprint linenums lang-js'><code>var DB1 = patio.createConnection("my://connection/string");
var DB2 = patio.createConnection("my://connection/string2");
//user table in db1
var User1 = patio.addModel(DB1.from("user"));
//user table in db2
var User2 = patio.addModel(DB2.from("user"));
patio.syncModels().then(function(User1,User2){
var myUser1 = new User1({
firstName : "Bob1",
lastName : "Yukon1",
password : "password",
dateOfBirth : new Date(1980, 8, 29)
});
var myUser2 = new User2({
firstName : "Bob2",
lastName : "Yukon2",
password : "password",
dateOfBirth : new Date(1980, 8, 29)
});
comb.when(myUser1.save(), myUser2.save(), function(saved){
console.log(format("%s %s was created at %s", myUser1.firstName, myUser1.lastName, myUser1.created.toString()));
console.log(format("%s %s's id is %d", myUser1.firstName, myUser1.lastName, myUser1.id));
console.log(format("%s %s was created at %s", myUser2.firstName, myUser2.lastName,myUser2.created.toString()));
console.log(format("%s %s's id is %d", myUser2.firstName, myUser2.lastName, myUser2.id));
});
});</code></pre>
<h2>Custom setters and getters</h2>
<h3>Setters</h3>
<p>patio creates setters and getters for each column in the database if you want alter the value of a particular property before its set on the model you can use a custom setter.
</p>
<p>For example if you wanted to ensure proper case and first and last name of a user:
</p>
<pre class='prettyprint linenums lang-js'><code>var User = patio.addModel("user", {
instance : {
_setFirstName : function(firstName){
return firstName.charAt(0).toUpperCase() + firstName.substr(1);
},
_setLastName : function(lastName){
return lastName.charAt(0).toUpperCase() + lastName.substr(1);
}
}
});
patio.syncModels().then(function(User){
var myUser = new User({
firstName : "bob",
lastName : "yukon"
});
console.log(myUser.firstName); //Bob
console.log(myUser.lastName); //Yukon
});</code></pre>
<h3>Getters</h3>
<p>Custom getters can be used to change values returned from the database but not alter the value when persisting.
</p>
<p>For example if you wanted to return a value as an array but persist as a string you could do the following.
</p>
<pre class='prettyprint linenums lang-js'><code>var User = patio.addModel("user", {
instance : {
_getRoles : function(roles){
return roles.split(",");
}
}
});
patio.syncModels().then(function(User){
var myUser = new User({
firstName : "bob",
lastName : "yukon",
roles : "admin,user,groupAdmin"
});
console.log(myUser.roles); //['admin', 'user','groupAdmin'];
});</code></pre>
<p>You can also use the getters/setters in tandem.
</p>
<p>Lets take the getters example from before but use a setter also
</p>
<pre class='prettyprint linenums lang-js'><code>var User = patio.addModel("user", {
instance : {
_setRoles : function(roles){
return roles.join(",");
},
_getRoles : function(roles){
return roles.split(",");
}
}
});
patio.syncModels().then(function(User){
var myUser = new User({
firstName : "bob",
lastName : "yukon",
roles : ["admin","user","groupAdmin"];
});
console.log(myUser.roles); //['admin', 'user','groupAdmin'];
//INSERT INTO `user` (`first_name`, `last_name`, `roles`) VALUES ('bob', 'yukon', 'admin,user,groupAdmin')
myUser.save();
});</code></pre>
<h2>Model hooks</h2>
<p>Each model has the following hooks
</p>
<ul>
<li>pre<ul>
<li><strong>save<</strong> : called right before the model is saved to the database</li>
<li><strong>update</strong> : called right before the model is updated</li>
<li><strong>remove</strong> : called right before a model is deleted</li>
<li><strong>load</strong> : called right before a model is loaded with values from the database</li>
</ul>
</li>
<li>post<ul>
<li><strong>save<</strong> : called right after the model is saved to the database</li>
<li><strong>update</strong> : called right after the model is updated</li>
<li><strong>remove</strong> : called right after a model is deleted</li>
<li><strong>load</strong> : called right after a model is loaded with values from the database</li>
</ul>
</li>
</ul>
<pre class='prettyprint linenums lang-js'><code>var User = patio.addModel("user", {
pre:{
"save":function(next){
console.log("pre save!!!")
next();
},
"remove" : function(next){
console.log("pre remove!!!")
next();
}
},
post:{
"save":function(next){
console.log("post save!!!")
next();
},
"remove" : function(next){
console.log("post remove!!!")
next();
}
},
instance:{
_setFirstName:function(firstName){
return firstName.charAt(0).toUpperCase() + firstName.substr(1);
},
_setLastName:function(lastName){
return lastName.charAt(0).toUpperCase() + lastName.substr(1);
}
}
});</code></pre>
<h2>Using a model</h2>
<p>If you define a model you can either use the Models constructor directly.
</p>
<pre class='prettyprint linenums lang-js'><code>//define the model
var User = patio.addModel("user");
patio.syncModels(function(err){
if(err){
console.log(err.stack);
}else{
var user = new User();
}
})</code></pre>
<p>or you can use <code>patio.getModel</code>
</p>
<pre class='prettyprint linenums lang-js'><code>
patio.addModel("user");
patio.syncModels(function(err){
if(err){
console.log(err.stack);
}else{
var User = patio.getModel("user");
var user = new User();
}
})</code></pre>
<h3>Mutli Database Models</h3>
<p>If you are working with multiple databases and your model's table is not in the <a href=""./patio.html#defaultDatabase"">patio.defaultDatabase</a> (the first database you connected to) then you will need to pass in the database the model's table is in.
</p>
<pre class='prettyprint linenums lang-js'><code>var DB1 = patio.createConnection("my://connection/string");
var DB2 = patio.createConnection("my://connection/string2");
//user table in db1
var User1 = patio.addModel(DB1.from("user"));
//user table in db2
var User2 = patio.addModel(DB2.from("user"));
patio.syncModels(function(err){
if(err){
console.log(err.stack);
}else{
var user1 = new User1(),
user2 = new User2();
}
});</code></pre>
<h3>Creating</h3>
<p>The static <a href="./patio_Model.html#.save">save</a> can be used for saving a group of models at once. <strong>Note</strong> this method is not any more efficient than creating a model using new, just less verbose.
</p>
<pre class='prettyprint linenums lang-js'><code>var Student = patio.getModel("student");
Student.save([
{
firstName:"Bob",
lastName:"Yukon",
gpa:3.689,
classYear:"Senior"
},
{
firstName:"Greg",
lastName:"Horn",
gpa:3.689,
classYear:"Sophomore"
},
{
firstName:"Sara",
lastName:"Malloc",
gpa:4.0,
classYear:"Junior"
},
{
firstName:"John",
lastName:"Favre",
gpa:2.867,
classYear:"Junior"
},
{
firstName:"Kim",
lastName:"Bim",
gpa:2.24,
classYear:"Senior"
},
{
firstName:"Alex",
lastName:"Young",
gpa:1.9,
classYear:"Freshman"
}
]).then(function(users){
//All users have been saved
}, disconnectError);</code></pre>
<p>When saving a group of models the save method will use a transaction unless the <code>useTransactions</code> property is set to false. You can manually override the useTransactions property by passing in an additional options parameter with a transaction value set to false.
</p>
<pre class='prettyprint linenums lang-js'><code>var Student = patio.getModel("student");
Student.save([
{
firstName:"Bob",
lastName:"Yukon",
gpa:3.689,
classYear:"Senior"
},
{
firstName:"Greg",
lastName:"Horn",
gpa:3.689,
classYear:"Sophomore"
}
], {transaction : false}).then(function(users){
//work with the users
});</code></pre>
<p>If you have an instance of a model then you can use the <a href="./patio_Model.html#save">save</a> method on the instance of the model.
</p>
<pre class='prettyprint linenums lang-js'><code>var myUser = new User({
firstName : "Bob",
lastName : "Yukon",
password : "password",
dateOfBirth : new Date(1980, 8, 29)
});
//save the user
myUser.save().then(function(user){
//the save is complete
}, disconnectError);</code></pre>
<p>You can also pass in values into the save method to set before saving.
</p>
<pre class='prettyprint linenums lang-js'><code>var myUser = new User();
//save the user
myUser.save({
firstName : "Bob",
lastName : "Yukon",
password : "password",
dateOfBirth : new Date(1980, 8, 29)
}).then(function(user){
//the save is complete
}, disconnectError);</code></pre>
<p>You can also pass in an options object to override options such as using a transaction.
</p>
<pre class='prettyprint linenums lang-js'><code>var myUser = new User();
//save the user
myUser.save({
firstName : "Bob",
lastName : "Yukon",
password : "password",
dateOfBirth : new Date(1980, 8, 29)
}, {transaction : false}).then(function(user){
//the save is complete
}, disconnectError);</code></pre>
<h3>Reading</h3>
<p>The Model contains static methods for all of the datasets methods listed in <a href="./patio_Dataset.html#.ACTION_METHODS">patio.Dataset.ACTION_METHODS</a> as well as all the methods listed in <a href="./patio_Dataset.html#.QUERY_METHODS">patio.Dataset.QUERY_METHODS</a>.
</p>
<p>Some of the most commonly used methods are:
</p>
<ul>
<li><a href="./patio_Dataset.html#forEach">forEach</a></li>
</ul>
<pre class='prettyprint linenums lang-js'><code>User.forEach(function(user){
console.log(user.firstName);
});
//you may also return the result of another query(or any promise) from a forEach block,
//this will prevent the forEach's promise from resolving until all actions that occured in the block have
//resolved.
var Blog = patio.addModel("blog");
User.forEach(funciton(user){
//create a blog for each user
return new Blog({userId : user.id}).save();
}).then(function(users){
//all users and blogs have been saved
}, disconnectError);</code></pre>
<ul>
<li><a href="./patio_Dataset.html#map">map</a></li>
</ul>
<pre class='prettyprint linenums lang-js'><code>User.map(function(user){
return user.firstName;
}).then(function(names){
console.log("User names are %s", names);
}, disconnectError);</code></pre>
<ul>
<li><a href="./patio_Dataset.html#all">all</a></li>
</ul>
<pre class='prettyprint linenums lang-js'><code>User.all().then(function(users){
console.log(users.length);
}, disconnectError);</code></pre>
<ul>
<li><a href="./patio_Dataset.html#filter">filter</a></li>
</ul>
<pre class='prettyprint linenums lang-js'><code>//find all users where first names begin with bo case insensitive
User.filter({firstName : /^bo/i}).all().then(function(){
}, disconnectError);</code></pre>
<ul>
<li><a href="./patio_Dataset.html#one">one</a></li>
</ul>
<pre class='prettyprint linenums lang-js'><code>User.filter({id : 1}).one().then(function(user){
console.log("%d - %s %s", user.id, user.firstName, user.lastName);
}, disconnectError);</code></pre>
<ul>
<li><a href="./patioDataset.html#first">first</a></li>
</ul>
<pre class='prettyprint linenums lang-js'><code>//SELECT * FROM user WHERE first_name = 'bob' ORDER BY last_name LIMIT 1
User.filter({firstName : "bob"}).order("lastName").first().then(function(user){
console.log("%d - %s %s", user.id, user.firstName, user.lastName);
}, disconnectError);</code></pre>
<ul>
<li><a href="./patio_Dataset.html#last">last</a></li>
</ul>
<pre class='prettyprint linenums lang-js'><code>//SELECT * FROM user WHERE first_name = 'bob' ORDER BY last_name DESC LIMIT 1
User.filter({firstName : "bob"}).order("lastName").last().then(function(user){
console.log("%d - %s %s", user.id, user.firstName, user.lastName);
}, disconnectError);</code></pre>
<ul>
<li><a href="./patio_Dataset.html#isEmpty">isEmpty</a></li>
</ul>
<pre class='prettyprint linenums lang-js'><code>
User.isEmpty().then(function(isEmpty){
if(isEmpty){
console.log("user table is empty");
}else{
console.log("user table is not empty");
}
}, disconnectError);</code></pre>
<h3>Updating</h3>
<p>The static <a href="./patio_Model.html#.update">update</a> can be used for updating a batch of models.
</p>
<pre class='prettyprint linenums lang-js'><code> //BEGIN
//UPDATE `user` SET `password` = NULL
//COMMIT
User.update({password : null});</code></pre>
<p>You can also pass in a query to limit the models that are updated. The filter can be anything that <a href="./patio_Dataset.html#filter">filter</a> accepts.
</p>
<pre class='prettyprint linenums lang-js'><code>User.update({password : null}, function(){
return this.lastAccessed.lte(comb.yearsAgo(1));
});
//same as
User.update({password : null}, {lastAccess : {lte : comb.yearsAgo(1)}});</code></pre>
<p>To prevent default transaction behavior you can pass in an additional transaction option
</p>
<pre class='prettyprint linenums lang-js'><code>User.update({password : null}, {lastAccess : {lte : comb.yearsAgo(1)}}, {transaction : false});</code></pre>
<p>If you have an instance of a model and you want to update it you can use the <a href="./patio_Model.html#update">update</a> instance method.
</p>
<pre class='prettyprint linenums lang-js'><code>var updateUsers = User.forEach(function(user){
//returning the promise from update will cause the forEach not to resolve
//until all updates have completed
return user.update({fullName : user.firstName + " " + user.lastName});
});
updateUsers.then(function(){
//updates finished
});</code></pre>
<p>as with save you can pass in an options object to prevent default behavior such as transactions.
</p>
<pre class='prettyprint linenums lang-js'><code>var updateUsers = User.forEach(function(user){
//returning the promise from update will cause the forEach not to resolve
//until all updates have completed
return user.update({fullName : user.firstName + " " + user.lastName}, {transaction : false});
});
updateUsers.then(function(){
//updates finished
});</code></pre>
<h3>Deleting</h3>
<p>The static <a href="./patio_Model.html#.remove">remove</a> can be used for removing a batch of models. <strong>Note</strong> this method is not anymore efficient just a convenience.
</p>
<pre class='prettyprint linenums lang-js'><code>//remove all models
User.remove();</code></pre>