-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDB.cls
94 lines (82 loc) · 2.59 KB
/
DB.cls
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
/**
* Apex database layer for managed packages to simplify and enforce FLS
*
* Author: @aldoforce
* Github: github.com/aldoforce/apex-db-manager
* License: GNU GPLv2 http://www.gnu.org/licenses/gpl-2.0.html
*
**/
public with sharing class DB {
/** Insert operation **********************************************************/
public static void inserter(SObject[] pSObjects) {
if ( pSObjects != null && pSObjects.size() > 0 )
if ( pSObjects[0].getSObjectType().getDescribe().isCreateable() )
//dml
insert pSObjects;
else
DB.raiseException(pSObjects[0], 'inserter');
}
public static void inserter(SObject pSObject) {
DB.inserter(
new SObject[]{ pSObject }
);
}
/** Update operation **********************************************************/
public static void updater(SObject[] pSObjects) {
if ( pSObjects != null && pSObjects.size() > 0 )
if ( pSObjects[0].getSObjectType().getDescribe().isUpdateable() )
//dml
update pSObjects;
else
DB.raiseException(pSObjects[0], 'updater');
}
public static void updater(SObject pSObject) {
DB.updater(
new SObject[]{ pSObject }
);
}
/** Upsert operation **********************************************************/
public static void upserter(SObject[] pSObjects) {
if ( pSObjects != null && pSObjects.size() > 0 )
if ( pSObjects[0].getSObjectType().getDescribe().isCreateable() &&
pSObjects[0].getSObjectType().getDescribe().isUpdateable() )
//dml
DB.upsert_dml(pSObjects);
else
DB.raiseException(pSObjects[0], 'upsert');
}
public static void upserter(SObject pSObject) {
DB.upserter(
new SObject[]{ pSObject }
);
}
/** Upsert specific DML operation based on sObject Id *************************/
private static void upsert_dml(SObject[] pSObjects) {
//containers
SObject[] pInsert = new SObject[]{};
SObject[] pUpdate = new SObject[]{};
//collect and classify
for (SObject s : pSObjects)
if (s.get('id') == null)
pInsert.add(s);
else
pUpdate.add(s);
//dmls
insert pInsert;
update pUpdate;
}
/** generic exception ********************************************************/
private static void raiseException(SObject pSObject, String pOperation) {
throw new DBException(
String.format(
'The {0} operation is not allowed because the SObject "{1}" is not accessible for the running user/context',
new String[] {
pOperation,
pSObject.getSObjectType().getDescribe().getName()
}
)
);
}
/** DB inner exception *******************************************************/
public class DBException extends Exception{}
}