diff --git a/entity/Person_entity/Person_entity.aod b/entity/Person_entity/Person_entity.aod index 9261c6e57bcedd0d2ce89ae367a3f453fe0eebd7..259a74271e2e0cecb5702dbcd9d7c4cb2b4181b5 100644 --- a/entity/Person_entity/Person_entity.aod +++ b/entity/Person_entity/Person_entity.aod @@ -1107,6 +1107,10 @@ Usually this is used for filtering COMMUNICATION-entries by a specified contact <name>STANDARD_COUNTRY</name> <valueProcess>%aditoprj%/entity/Person_entity/entityfields/standard_country/valueProcess.js</valueProcess> </entityField> + <entityActionField> + <name>ActionField</name> + <onActionProcess>%aditoprj%/entity/Person_entity/entityfields/actionfield/onActionProcess.js</onActionProcess> + </entityActionField> </entityFields> <recordContainers> <dbRecordContainer> diff --git a/entity/Person_entity/entityfields/actionfield/onActionProcess.js b/entity/Person_entity/entityfields/actionfield/onActionProcess.js new file mode 100644 index 0000000000000000000000000000000000000000..5b17566efe0d0a60c44847b2e3aecd4d54c2692c --- /dev/null +++ b/entity/Person_entity/entityfields/actionfield/onActionProcess.js @@ -0,0 +1 @@ +import("SqlLib_tests"); \ No newline at end of file diff --git a/language/_____LANGUAGE_de/_____LANGUAGE_de.aod b/language/_____LANGUAGE_de/_____LANGUAGE_de.aod index 7ff6c052b349cb3dc409186f74a1625810eef6f3..83e26d975465e9997a980ffdbe82499de58c36a4 100644 --- a/language/_____LANGUAGE_de/_____LANGUAGE_de.aod +++ b/language/_____LANGUAGE_de/_____LANGUAGE_de.aod @@ -6120,6 +6120,7 @@ </entry> <entry> <key>Links</key> + <value>Verknüpfungen</value> </entry> <entry> <key>Set dunning</key> diff --git a/neonView/ActivityPreview_view/ActivityPreview_view.aod b/neonView/ActivityPreview_view/ActivityPreview_view.aod index bef0d230ae7a9083ab31796e0a912b215c2605ca..a55312a91ea85555c4bc7fb90afb971e4342cb64 100644 --- a/neonView/ActivityPreview_view/ActivityPreview_view.aod +++ b/neonView/ActivityPreview_view/ActivityPreview_view.aod @@ -20,6 +20,7 @@ <genericViewTemplate> <name>Info</name> <showDrawer v="true" /> + <drawerCaption>Details</drawerCaption> <entityField>#ENTITY</entityField> <fields> <entityFieldLink> diff --git a/neonView/AttributePreview_view/AttributePreview_view.aod b/neonView/AttributePreview_view/AttributePreview_view.aod index 1b47431cd77698dabfe8af1ae6038e8d2f3f1e0b..17d92b13f9d27feac4c338084eb99cc1062ea8fa 100644 --- a/neonView/AttributePreview_view/AttributePreview_view.aod +++ b/neonView/AttributePreview_view/AttributePreview_view.aod @@ -19,6 +19,7 @@ <genericViewTemplate> <name>Details</name> <showDrawer v="true" /> + <drawerCaption>Details</drawerCaption> <entityField>#ENTITY</entityField> <fields> <entityFieldLink> diff --git a/neonView/BulkMailPreview_view/BulkMailPreview_view.aod b/neonView/BulkMailPreview_view/BulkMailPreview_view.aod index 2562211c30a9bfcd975a09d133fc2d525fbd9e70..cb4871218055cb024bd1f17c333ac01e11e98d35 100644 --- a/neonView/BulkMailPreview_view/BulkMailPreview_view.aod +++ b/neonView/BulkMailPreview_view/BulkMailPreview_view.aod @@ -20,6 +20,7 @@ <genericViewTemplate> <name>Generic</name> <showDrawer v="true" /> + <drawerCaption>Details</drawerCaption> <entityField>#ENTITY</entityField> <fields> <entityFieldLink> diff --git a/neonView/CampaignPreview_view/CampaignPreview_view.aod b/neonView/CampaignPreview_view/CampaignPreview_view.aod index 74073d0218b2be07d66c0d58ff1c13fcf22b6c94..6d79075ca4218f8dfd3d35bb633cc5bc473ab4d1 100644 --- a/neonView/CampaignPreview_view/CampaignPreview_view.aod +++ b/neonView/CampaignPreview_view/CampaignPreview_view.aod @@ -47,6 +47,7 @@ <genericViewTemplate> <name>Description</name> <showDrawer v="true" /> + <drawerCaption>Further informations</drawerCaption> <entityField>#ENTITY</entityField> <title>Beschreibung</title> <fields> diff --git a/neonView/DuplicateScannerPreview_view/DuplicateScannerPreview_view.aod b/neonView/DuplicateScannerPreview_view/DuplicateScannerPreview_view.aod index 3aee7953eaafdcc5e5b16f30dd500e8ccc072d72..8e00e58e5fcb9427672a3b53a7de56fdafedeaba 100644 --- a/neonView/DuplicateScannerPreview_view/DuplicateScannerPreview_view.aod +++ b/neonView/DuplicateScannerPreview_view/DuplicateScannerPreview_view.aod @@ -11,6 +11,7 @@ <genericViewTemplate> <name>asd</name> <showDrawer v="true" /> + <drawerCaption>Details</drawerCaption> <entityField>#ENTITY</entityField> <fields> <entityFieldLink> diff --git a/neonView/EmployeePreview_view/EmployeePreview_view.aod b/neonView/EmployeePreview_view/EmployeePreview_view.aod index ef773cde44a993d2c975ba54dee5239158b2736e..d986a73ca51961645e30c3fa707b6a34d080d715 100644 --- a/neonView/EmployeePreview_view/EmployeePreview_view.aod +++ b/neonView/EmployeePreview_view/EmployeePreview_view.aod @@ -19,6 +19,7 @@ <genericViewTemplate> <name>Info</name> <showDrawer v="true" /> + <drawerCaption>Details</drawerCaption> <entityField>#ENTITY</entityField> <fields> <entityFieldLink> diff --git a/neonView/KeywordEntryPreview_view/KeywordEntryPreview_view.aod b/neonView/KeywordEntryPreview_view/KeywordEntryPreview_view.aod index c96fa8461529a7cd2f5d2c2f38221d6f188cba49..af89bc57b2674f91f2ed46048b56c428243a85fe 100644 --- a/neonView/KeywordEntryPreview_view/KeywordEntryPreview_view.aod +++ b/neonView/KeywordEntryPreview_view/KeywordEntryPreview_view.aod @@ -19,6 +19,7 @@ <genericViewTemplate> <name>Info</name> <showDrawer v="true" /> + <drawerCaption>Details</drawerCaption> <entityField>#ENTITY</entityField> <title></title> <fields> diff --git a/neonView/OfferPreview_view/OfferPreview_view.aod b/neonView/OfferPreview_view/OfferPreview_view.aod index 371fc562762549ffa99d28ce5e9803111dcee429..d75cbe594b35d9d5e8bf7f6e89c85b10b262647f 100644 --- a/neonView/OfferPreview_view/OfferPreview_view.aod +++ b/neonView/OfferPreview_view/OfferPreview_view.aod @@ -69,6 +69,7 @@ <genericViewTemplate> <name>Info</name> <showDrawer v="true" /> + <drawerCaption>Further informations</drawerCaption> <entityField>#ENTITY</entityField> <fields> <entityFieldLink> diff --git a/neonView/OrderPreview_view/OrderPreview_view.aod b/neonView/OrderPreview_view/OrderPreview_view.aod index a5c5761ef0f2690cad4a2f814d523e028828bb30..d8011fc3f68ac92e19af97a92d505524514c80b0 100644 --- a/neonView/OrderPreview_view/OrderPreview_view.aod +++ b/neonView/OrderPreview_view/OrderPreview_view.aod @@ -97,6 +97,7 @@ <genericViewTemplate> <name>Info</name> <showDrawer v="true" /> + <drawerCaption>Links</drawerCaption> <entityField>#ENTITY</entityField> <fields> <entityFieldLink> diff --git a/neonView/OrganisationPreview_view/OrganisationPreview_view.aod b/neonView/OrganisationPreview_view/OrganisationPreview_view.aod index 9781eefd461fce6883e9c4368ab1de3fcd7f4a6b..c07d5201a1d6d499a029f4656939fc61607af2df 100644 --- a/neonView/OrganisationPreview_view/OrganisationPreview_view.aod +++ b/neonView/OrganisationPreview_view/OrganisationPreview_view.aod @@ -49,6 +49,7 @@ <genericViewTemplate> <name>Info</name> <showDrawer v="true" /> + <drawerCaption>Further informations</drawerCaption> <entityField>#ENTITY</entityField> <fields> <entityFieldLink> diff --git a/neonView/PersonPreview_view/PersonPreview_view.aod b/neonView/PersonPreview_view/PersonPreview_view.aod index 010b9642488c37f53eff2efd2dc2d9a89974f94f..14e33c7404fb9ab854e3564f98c4cc1df0cf6d0b 100644 --- a/neonView/PersonPreview_view/PersonPreview_view.aod +++ b/neonView/PersonPreview_view/PersonPreview_view.aod @@ -36,7 +36,10 @@ <genericViewTemplate> <name>Info</name> <showDrawer v="true" /> + <drawerCaption>Further informations</drawerCaption> + <fixedDrawer v="false" /> <entityField>#ENTITY</entityField> + <devices /> <fields> <entityFieldLink> <name>f9875d78-3d72-47d3-b729-9cf80d236f6e</name> diff --git a/neonView/ProductpricePreview_view/ProductpricePreview_view.aod b/neonView/ProductpricePreview_view/ProductpricePreview_view.aod index b5039c392066e51b42601d3dcca9df5d352a3ea3..191f70d7ada00413637a3a6354a23e76dc8160d4 100644 --- a/neonView/ProductpricePreview_view/ProductpricePreview_view.aod +++ b/neonView/ProductpricePreview_view/ProductpricePreview_view.aod @@ -12,6 +12,7 @@ <genericViewTemplate> <name>PriceInfo</name> <showDrawer v="true" /> + <drawerCaption>Details</drawerCaption> <entityField>#ENTITY</entityField> <fields> <entityFieldLink> diff --git a/neonView/RolePreview_view/RolePreview_view.aod b/neonView/RolePreview_view/RolePreview_view.aod index c292b9f37d4db1e5a808dd474808959f87a4e406..f31226f844021b0d984ade46057e6b3bad876d53 100644 --- a/neonView/RolePreview_view/RolePreview_view.aod +++ b/neonView/RolePreview_view/RolePreview_view.aod @@ -17,6 +17,7 @@ </cardViewTemplate> <genericViewTemplate> <name>Generic</name> + <drawerCaption>Details</drawerCaption> <entityField>#ENTITY</entityField> <fields> <entityFieldLink> diff --git a/neonView/SerialLetterPreview_view/SerialLetterPreview_view.aod b/neonView/SerialLetterPreview_view/SerialLetterPreview_view.aod index 6454cf3bf79e4e29f5220f94592c211f172ddec6..c70b6eb3b7ddca907081773f1d10397c35ad5ba5 100644 --- a/neonView/SerialLetterPreview_view/SerialLetterPreview_view.aod +++ b/neonView/SerialLetterPreview_view/SerialLetterPreview_view.aod @@ -19,6 +19,8 @@ <genericViewTemplate> <name>Generic</name> <showDrawer v="true" /> + <drawerCaption>Details</drawerCaption> + <fixedDrawer v="false" /> <entityField>#ENTITY</entityField> <fields> <entityFieldLink> diff --git a/neonView/SupportTicketPreview_view/SupportTicketPreview_view.aod b/neonView/SupportTicketPreview_view/SupportTicketPreview_view.aod index 638242895cde2ec0c46d8583103eb64c36bba52f..b2b4df195fbf6956aeb2bc51d4058d4a813d43d6 100644 --- a/neonView/SupportTicketPreview_view/SupportTicketPreview_view.aod +++ b/neonView/SupportTicketPreview_view/SupportTicketPreview_view.aod @@ -20,6 +20,8 @@ <genericViewTemplate> <name>Info</name> <showDrawer v="true" /> + <drawerCaption>Details</drawerCaption> + <fixedDrawer v="false" /> <entityField>#ENTITY</entityField> <fields> <entityFieldLink> diff --git a/neonView/TaskPreview_view/TaskPreview_view.aod b/neonView/TaskPreview_view/TaskPreview_view.aod index f4cc5cda26e7d1cb2b3f7aeafb6ed8d0a51cae70..1ead0930f301e98a39047c1d1bf8d694c8a65aa0 100644 --- a/neonView/TaskPreview_view/TaskPreview_view.aod +++ b/neonView/TaskPreview_view/TaskPreview_view.aod @@ -19,6 +19,7 @@ <genericViewTemplate> <name>Info</name> <showDrawer v="true" /> + <drawerCaption>Details</drawerCaption> <entityField>#ENTITY</entityField> <fields> <entityFieldLink> diff --git a/process/Classification_lib/process.js b/process/Classification_lib/process.js index eeb17f665f07de2fc81ee1452e04ff811b272a66..126a6dde2d44fd2fa1f2421e7f4dcab7acbc13c9 100644 --- a/process/Classification_lib/process.js +++ b/process/Classification_lib/process.js @@ -96,7 +96,7 @@ ClassificationUtils.mapToClass = function(pScore) ClassificationUtils.getAllGroups = function(pClassificationtype, pTwoCol) { var sql = new SqlBuilder() - .selectDistinct(["CLASSIFICATIONGROUP", (pTwoCol ? "CLASSIFICATIONGROUP" : "")]) + .select(["distinct CLASSIFICATIONGROUP", (pTwoCol ? "CLASSIFICATIONGROUP" : "")]) .from("CLASSIFICATIONTYPE") .where("CLASSIFICATIONTYPE.CLASSIFICATIONTYPE", pClassificationtype) .orderBy("CLASSIFICATIONGROUP"); diff --git a/process/Context_lib/process.js b/process/Context_lib/process.js index 84c5890a0269cc275de1d3cdd443a18ac71ad1ac..e9ad1638d401a0e4aceafd4970c456bf81581aa0 100644 --- a/process/Context_lib/process.js +++ b/process/Context_lib/process.js @@ -214,7 +214,7 @@ function ContextSelector(pTableName, pIdField, pTitleExpression) /** * title-definition; db-column or another sql-expression (like concating fields) as long as it returns one field * read-only property; set it with a matching setter - * @property + * @property titleExpression */ this.titleExpression = null; ProtoPropertyUtils.makeSemiReadOnly(this, "titleExpression"); this.setTitleExpression(pTitleExpression); @@ -222,7 +222,7 @@ function ContextSelector(pTableName, pIdField, pTitleExpression) /** * name of the database-table * read-only property; set it with a matching setter - * @property + * @property tableName */ this.tableName = null; ProtoPropertyUtils.makeSemiReadOnly(this, "tableName"); this.setTableName(pTableName); @@ -230,7 +230,7 @@ function ContextSelector(pTableName, pIdField, pTitleExpression) /** * db-field for the ID of one record (UID of matching context) * read-only property; set it with a matching setter - * @property + * @property idField */ this.idField = null; ProtoPropertyUtils.makeSemiReadOnly(this, "idField"); this.setIdField(pIdField); @@ -238,31 +238,31 @@ function ContextSelector(pTableName, pIdField, pTitleExpression) /** * expression for additional joins to be made (addotopmaö pt table-name) * read-only property; set it with a matching setter - * @property + * @property joinExpression */ this.joinExpression = null; ProtoPropertyUtils.makeSemiReadOnly(this, "joinExpression"); /** * db-field for the ID of the relation to a CONTACT-record * read-only property; set it with a matching setter - * @property + * @property contactIdField */ this.contactIdField = null; ProtoPropertyUtils.makeSemiReadOnly(this, "contactIdField"); /** * db-field that represents the date of creation * read-only property; set it with a matching setter - * @property + * @property creationDateField */ this.creationDateField = null; ProtoPropertyUtils.makeSemiReadOnly(this, "creationDateField"); /** * db-field where the STATE-information (active/inactive) is stored (see the activeStates-property) * read-only property; set it with a matching setter - * @property + * @property stateField */ this.stateField = null; ProtoPropertyUtils.makeSemiReadOnly(this, "stateField"); /** * array that contains IDs of states that represent an "active"-state * read-only property; set it with a matching setter - * @property + * @property activeStates */ this.activeStates = null; ProtoPropertyUtils.makeSemiReadOnly(this, "activeStates"); this.condition = null; ProtoPropertyUtils.makeSemiReadOnly(this, "condition"); @@ -276,7 +276,7 @@ function ContextSelector(pTableName, pIdField, pTitleExpression) * "Offer" ... // you can add as many subcontexts as you wish * } * read-only property; set it with a matching setter - * @property + * @property subContexts */ this.subContexts = null; ProtoPropertyUtils.makeSemiReadOnly(this, "subContexts"); } diff --git a/process/SqlLib_tests/process.js b/process/SqlLib_tests/process.js index c6a50cae3d8066a741a0b00790701af67c682039..4d7bb4e705683bf59fe1163f8c6ab5561d309c83 100644 --- a/process/SqlLib_tests/process.js +++ b/process/SqlLib_tests/process.js @@ -80,6 +80,14 @@ var validAndUsageTests = new TestSuite([ pTester.assert("( PERSON.FIRSTNAME = 'Tim' ) ", actual.toString()); }], + ["$ should be escaped by a second $ and the string should therefore just be used as string and not as jdito variable", function(pTester) + { + var actual = new SqlBuilder() + .where("PERSON.FIRSTNAME", "$$mySuperString") + + pTester.assert("( PERSON.FIRSTNAME = '$mySuperString' ) ", actual.toString()); + }], + ["and should add a condition if value is a jdito-var containing an empty string", function(pTester) { vars.set("$global.TestingVarEmptyString", ""); @@ -119,7 +127,7 @@ var validAndUsageTests = new TestSuite([ { var actual = new SqlBuilder() .where([ - "PERSON.FIRSTNAME = '?", [["Peter", db.get]] + "PERSON.FIRSTNAME = ?", [["Peter", 12]] ]) .and([ "exists (select * FROM CONTACT where PERSON_ID = PERSONID)", [] @@ -133,6 +141,8 @@ var validAndUsageTests = new TestSuite([ { var actual = new SqlBuilder() .where(new SqlBuilder() + .select("TEST") + .from("PERSON") .where("PERSON.FIRSTNAME", "Tim") .and("PERSON.LASTNAME", "Admin")) @@ -777,7 +787,7 @@ var testConstantFunctions = new TestSuite([ ]); var selectTests = new TestSuite([ - ["test if a sql-builder in a fields-array is translated to sql correctly", function(pTester) + ["a sql-builder in a fields-array is translated to sql correctly", function(pTester) { var countSubQuery = newSelect("count(*)") .from("AB_ATTRIBUTEUSAGE") @@ -791,6 +801,66 @@ var selectTests = new TestSuite([ pTester.assert("select AB_ATTRIBUTEID, AB_ATTRIBUTEUSAGEID, (select count(*) from AB_ATTRIBUTEUSAGE where AB_ATTRIBUTEUSAGE.OBJECT_TYPE = ? and AB_ATTRIBUTEUSAGE.AB_ATTRIBUTE_ID = AB_ATTRIBUTE.AB_ATTRIBUTEID)", actual._select._sqlStorage, "prepared select-sql"); pTester.assert(1, actual._select.preparedValues.length, "number of params"); }], + + ["a sql-builder in from is used as subselect", function(pTester) + { + var subQuery = newSelect("FIRSTNAME") + .from("PERSON") + .where("PERSON.LASTNAME", "Meier") + + var actual = new SqlBuilder() + .select("*") + .from(subQuery) + + pTester.assert("from (select FIRSTNAME from PERSON where PERSON.LASTNAME = ?)", actual._from._sqlStorage, "prepared select-sql"); + pTester.assert(1, actual._from.preparedValues.length, "number of params"); + }] +]); + +var joinTests = new TestSuite([ + ["SqlBuilder as on-condition should only add the conditon of the builder", function(pTester) + { + var subQuery = newSelect("NAME") + .from("ORGANISATION") + .where("ORGANISATION.NAME", "Adito") + + var actual = new SqlBuilder() + .select("*") + .from("PERSON") + .join("ORGANISATION", subQuery) + + logging.log(JSON.stringify([actual._joins], null, "\t")) + pTester.assert("join ORGANISATION on ORGANISATION.NAME = ?", actual._joins[0]._sqlStorage, "prepared select-sql"); + pTester.assert(1, actual._joins[0].preparedValues.length, "number of params"); + }], + + ["SqlBuilder as table for join is added as subselect", function(pTester) + { + var subQuery = newSelect("NAME") + .from("ORGANISATION") + .where("ORGANISATION.NAME", "Adito") + + var actual = new SqlBuilder() + .select("*") + .from("PERSON") + .join(subQuery, "orgname.NAME = TABLE2.NAME", "orgname") + + logging.log(JSON.stringify([actual._joins], null, "\t")) + pTester.assert("join (select NAME from ORGANISATION where ORGANISATION.NAME = ?) orgname on orgname.NAME = TABLE2.NAME", actual._joins[0]._sqlStorage, "prepared select-sql"); + pTester.assert(1, actual._joins[0].preparedValues.length, "number of params"); + }], + + ["just use a string also containing a condition as join without additional condition", function(pTester) + { + var actual = new SqlBuilder() + .select("*") + .from("PERSON") + .join("TABLE1 on TABLE1.NAME = TABLE2.NAME") + + logging.log(JSON.stringify([actual._joins], null, "\t")) + pTester.assert("join TABLE1 on TABLE1.NAME = TABLE2.NAME", actual._joins[0]._sqlStorage, "prepared select-sql"); + pTester.assert(0, actual._joins[0].preparedValues.length, "number of params"); + }] ]) var tester = new Tester("Test SqlBuilder"); @@ -804,6 +874,7 @@ tester.test(mandatoryErrorTests); tester.test(inStatementTests); tester.test(testConstantFunctions); tester.test(selectTests); +tester.test(joinTests); logging.log("-------------------------"); tester.printResults(); diff --git a/process/Sql_lib/process.js b/process/Sql_lib/process.js index 729e428f310070d90554d89204e13e9c64ef0e06..a4cf96d6be498a7fc8db3ac2bddbe43c095e1173 100644 --- a/process/Sql_lib/process.js +++ b/process/Sql_lib/process.js @@ -12,10 +12,10 @@ import("Util_lib"); /** * Creates a new SqlBuilder object and sets the select clause of the sql. * - * @param {String|Array|SqlBuilder} pFields You can pass: - * - A String is just used AS IT IS. - * - The array can also contain Strings, SqlBuilder which are just concatenated - * - SqlBuilder is used as Subquery + * @param {String|Array|SqlBuilder} pFields You can pass:<br/> + * - A String is just used AS IT IS. (e.g. "FIRSTNAME, LASTNAME")<br/> + * - SqlBuilder is used as Subquery<br/> + * - The array can also contain Strings, SqlBuilder which are just concatenated (e.g. ["FIRSTNAME", "LASTNAME", someSqlBuilderContainingFullSelect])<br/> * Please see .select() for more information and examples. * @param {String} [pAlias=currentAlias] This alias is used for fetching the ColumnTypes and also for the .table, .cell, .updateData, ... -functions * @return {SqlBuilder} A new SqlBuilder object already containing the provided fields @@ -26,67 +26,67 @@ function newSelect(pFields, pAlias) } /** - * Creates a new SqlBuilder object and calls .where on it. - * This is very useful if you just need a condition as you can pass the first condition directly. - * Note: Even if you ommit all parameters, you do not have to call .where again. You can directly write .and / .or after newWhere(). + * Creates a new SqlBuilder object and calls .where on it.<br/> + * This is very useful if you just need a condition as you can pass the first condition directly.<br/> + * Note: Even if you ommit all parameters, you do not have to call .where again. You can directly write .and / .or after newWhere().<br/> * - * @param {String|String[]|SqlBuilder|PreparedSqlArray} [pFieldOrCond] If this is the only parameter, it is used as Subselect - * else it is used as Field. + * @param {String|String[]|SqlBuilder|PreparedSqlArray} [pFieldOrCond] If this is the only parameter, it is used as Subselect <br/> + * else it is used as Field. <br/> * Please see .where() for more information and examples. - * @param {String|SqlBuilder|PreparedSqlArray|Array|OtherTypes} [pValue] This is the value whitch is used for the condition. - * Basically it can be nearly everything you need. + * @param {String|SqlBuilder|PreparedSqlArray|Array|OtherTypes} [pValue] This is the value whitch is used for the condition.<br/> + * Basically it can be nearly everything you need.<br/> * Please see .where() for more information and examples. - * @param {String} [pCond="#=?"] This is the condition which should be used. - * # will be replaced by the field (pFieldOrCond) If pFieldOrCond is null, you can ommit # - * ? will be replaced by pValue + * @param {String} [pCondition="# = ?"] This is the condition which should be used.<br/> + * # will be replaced by the field (pFieldOrCond) If pFieldOrCond is null, you can ommit #<br/> + * ? will be replaced by pValue<br/> * Please see .where() for more information and examples. - * @param {SQLTYPES|Numeric} [pFieldType=AutomaticallyLoadedType] You can specify which datatype should be used for the prepared statement - * In most cases you don't need this. + * @param {SQLTYPES|Numeric} [pFieldType=AutomaticallyLoadedType] You can specify which datatype should be used for the prepared statement<br/> + * In most cases you don't need this.<br/> * Please see .where() for more information and examples. * @param {String} [pAlias=currentAlias] This alias is used for fetching the ColumnTypes and also for the .table, .cell, .updateData, ... -functions * @return {SqlBuilder} A new SqlBuilder object which already called .where */ -function newWhere(pFieldOrCond, pValue, pCond, pFieldType, pAlias) +function newWhere(pFieldOrCond, pValue, pCondition, pFieldType, pAlias) { - return new SqlBuilder(pAlias).where(pFieldOrCond, pValue, pCond, pFieldType); + return new SqlBuilder(pAlias).where(pFieldOrCond, pValue, pCondition, pFieldType); } /** - * Creates a new SqlBuilder object and calls .whereIfSet on it. - * This is very useful if you just need a condition as you can pass the first condition directly. + * Creates a new SqlBuilder object and calls .whereIfSet on it.<br/> + * This is very useful if you just need a condition as you can pass the first condition directly.<br/> * Note: Even if you ommit all parameters, you do not have to call .whereIfSet again. You can directly write .and / .or after newWhere(). * - * @param {String|String[]|SqlBuilder|PreparedSqlArray} [pFieldOrCond] If this is the only parameter, it is used as Subselect - * else it is used as Field. + * @param {String|String[]|SqlBuilder|PreparedSqlArray} [pFieldOrCond] If this is the only parameter, it is used as Subselect <br/> + * else it is used as Field. <br/> * Please see .whereIfSet() for more information and examples. - * @param {String|SqlBuilder|PreparedSqlArray|Array|OtherTypes} [pValue] This is the value whitch is used for the condition. - * Basically it can be nearly everything you need. + * @param {String|SqlBuilder|PreparedSqlArray|Array|OtherTypes} [pValue] This is the value whitch is used for the condition.<br/> + * Basically it can be nearly everything you need.<br/> * Please see .whereIfSet() for more information and examples. - * @param {String} [pCond="#=?"] This is the condition which should be used. - * # will be replaced by the field (pFieldOrCond) If pFieldOrCond is null, you can ommit # - * ? will be replaced by pValue + * @param {String} [pCondition="# = ?"] This is the condition which should be used.<br/> + * # will be replaced by the field (pFieldOrCond) If pFieldOrCond is null, you can ommit #<br/> + * ? will be replaced by pValue<br/> * Please see .whereIfSet() for more information and examples. - * @param {SQLTYPES|Numeric} [pFieldType=AutomaticallyLoadedType] You can specify which datatype should be used for the prepared statement - * In most cases you don't need this. + * @param {SQLTYPES|Numeric} [pFieldType=AutomaticallyLoadedType] You can specify which datatype should be used for the prepared statement<br/> + * In most cases you don't need this.<br/> * Please see .whereIfSet() for more information and examples. * @param {String} [pAlias=currentAlias] This alias is used for fetching the ColumnTypes and also for the .table, .cell, .updateData, ... -functions * @return {SqlBuilder} A new SqlBuilder object which already called .whereIfSet */ -function newWhereIfSet(pFieldOrCond, pValue, pCond, pFieldType, pAlias) +function newWhereIfSet(pFieldOrCond, pValue, pCondition, pFieldType, pAlias) { - return new SqlBuilder(pAlias).whereIfSet(pFieldOrCond, pValue, pCond, pFieldType); + return new SqlBuilder(pAlias).whereIfSet(pFieldOrCond, pValue, pCondition, pFieldType); } /** - * Object for building sqls. The main purpose of this is to make it easy to use prepared statements. - * You should ALWAYS use prepared statemnts for Security and maybe also for performance reasons. - * If you are not used to use prepared statements all the time you WILL forget to use it, when it's really needed. (eg. direct user input, not just ids) - * - * This can also be useful to build complex sqls where parts should be added - * dynamically while keeping the code clean. - * - * There exist some shortcut funtions - * - if you need a full select use newSelect(...) + * Object for building sqls. The main purpose of this is to make it easy to use prepared statements.<br/> + * You should ALWAYS use prepared statemnts for Security and maybe also for performance reasons.<br/> + * If you are not used to use prepared statements all the time you WILL forget to use it, when it's really needed. (eg. direct user input, not just ids)<br/> + * <br/> + * This can also be useful to build complex sqls where parts should be added<br/> + * dynamically while keeping the code clean.<br/> + * <br/> + * There exist some shortcut funtions<br/> + * - if you need a full select use newSelect(...)<br/> * - if you need only a condition use newWhere(...) or newWhereIfSet(...) * * @param {String} [pAlias=currentAlias] This alias is used for fetching the ColumnTypes and also for the .table, .cell, .updateData, ... -functions @@ -121,7 +121,7 @@ function SqlBuilder (pAlias) } /** - * Deep copies the SqlBuilder object and returns a new one. + * Deep copies the SqlBuilder object and returns a new one.<br/> * Use this if you want to add for example add additional parameters without modifying the current builder. * @return a full copy of the current SqlBuilder */ @@ -235,12 +235,12 @@ SqlBuilder.prototype.toString = function(pDefaultConditionIfNone) /** * Sets the select clause of the sql. - * @param {String|Array|SqlBuilder} pFields You can pass: - * - A String is just used AS IT IS. - * - The array can also contain Strings, SqlBuilder which are just concatenated - * - SqlBuilder is used as Subquery - * - *@return {SqlBuilder} current SqlBuilder object + * @param {String|Array|SqlBuilder} pFields You can pass:<br/> + * - A String is just used AS IT IS. (e.g. "FIRSTNAME, LASTNAME")<br/> + * - SqlBuilder is used as Subquery<br/> + * - The array can also contain Strings, SqlBuilder which are just concatenated (e.g. ["FIRSTNAME", "LASTNAME", someSqlBuilderContainingFullSelect]) + * + * @return {SqlBuilder} current SqlBuilder object */ SqlBuilder.prototype.select = function(pFields) { @@ -249,19 +249,13 @@ SqlBuilder.prototype.select = function(pFields) } /** - * Sets the select clause of the sql with distinct. - * @param {String|String[]} pFields - * @return {SqlBuilder} current SqlBuilder object - */ -SqlBuilder.prototype.selectDistinct = function(pFields) -{ - this._select = SqlBuilder._getStatement(pFields, "select distinct", undefined, true); - return this; -} - -/** - * Sets the from clause of the sql. - * @param {String|SqlBuilder} pTable + * Sets the from clause of the sql.<br/> + * <br/> + * Note: It is recommended to add joins via the .join functions.<br/> + * But in some cases you may already get a full from clause including the joins. In this case it is also possible to include them in the from-string.<br/> + * + * @param {String|SqlBuilder} pTable if it is a String, it is used as it is as table<br/> + * if it is a SqlBuilder, it is used as subselect: e.g. select * from (select FIRSTNAME from PERSON) * @param {String} [pTableAlias] table alias * @return {SqlBuilder} current SqlBuilder object */ @@ -275,16 +269,21 @@ SqlBuilder.prototype.from = function(pTable, pTableAlias) /** * Adds a join clause to the sql. - * @param {String|SqlBuilder} pTable - * @param {String|String[]|SqlBuilder} pCondition The where condition. This can be - * a string (without the where keyword), a SqlBuilder or an array (for prepared queries). - * @param {String} [pTableAlias] table alias +´* + * @param {String|SqlBuilder} pTable if it is a String, it is used as it is as table<br/> + * if it is a SqlBuilder, it is used as subselect: e.g. select * from Table1 join (select FIRSTNAME from PERSON) on ... + * @param {String|SqlBuilder} [pCondition] The where condition. This can be<br/> + * - a string (without the where keyword)<br/> + * - a SqlBuilder NOTE: only the condition is used from it + * + * @param {String} [pTableAlias] This alias is used to add an alias to the tablename * @param {String} [pPrefix] string before the join, for example "left", "right" + * @param {String} [pReplacementForWordJoin] if this is set, this is used instead of the word "join". Needed for e.g. OUTER APPLY in MSSQL * @return {SqlBuilder} current SqlBuilder object */ -SqlBuilder.prototype.join = function(pTable, pCondition, pTableAlias, pPrefix) +SqlBuilder.prototype.join = function(pTable, pCondition, pTableAlias, pPrefix, pReplacementForWordJoin) { - var prefix = "join"; + var prefix = (pReplacementForWordJoin ? pReplacementForWordJoin : "join"); if (pPrefix) prefix = pPrefix + " " + prefix; @@ -292,11 +291,21 @@ SqlBuilder.prototype.join = function(pTable, pCondition, pTableAlias, pPrefix) if (pTableAlias) postfix = pTableAlias + " " + postfix; + if (!pCondition) + postfix = ""; + var joinPart = SqlBuilder._getStatement(pTable, prefix, postfix); - var conditionPart = SqlBuilder._getStatement(pCondition); - joinPart._sqlStorage += " " + conditionPart._sqlStorage; - joinPart.preparedValues = joinPart.preparedValues.concat(conditionPart.preparedValues); + if (pCondition) + { + if (pCondition instanceof SqlBuilder) + pCondition = [pCondition._where._sqlStorage, pCondition._where.preparedValues] + + var conditionPart = SqlBuilder._getStatement(pCondition); + + joinPart._sqlStorage += " " + conditionPart._sqlStorage; + joinPart.preparedValues = joinPart.preparedValues.concat(conditionPart.preparedValues); + } this._joins.push(joinPart) return this; @@ -304,10 +313,14 @@ SqlBuilder.prototype.join = function(pTable, pCondition, pTableAlias, pPrefix) /** * Adds a left join clause to the sql. - * @param {String|SqlBuilder} pTable - * @param {String|String[]|SqlBuilder} pCondition The where condition. This can be - * a string (without the where keyword), a SqlBuilder or an array (for prepared queries). - * @param {String} [pTableAlias] table alias + * + * @param {String|SqlBuilder} pTable if it is a String, it is used as it is as table<br/> + * if it is a SqlBuilder, it is used as subselect: e.g. select * from Table1 join (select FIRSTNAME from PERSON) on ... + * @param {String|SqlBuilder} [pCondition] The where condition. This can be<br/> + * - a string (without the where keyword)<br/> + * - a SqlBuilder NOTE: only the condition is used from it + * + * @param {String} [pTableAlias] This alias is used to add an alias to the tablename * @return {SqlBuilder} current SqlBuilder object */ SqlBuilder.prototype.leftJoin = function(pTable, pCondition, pTableAlias) @@ -317,10 +330,14 @@ SqlBuilder.prototype.leftJoin = function(pTable, pCondition, pTableAlias) /** * Adds a right join clause to the sql. - * @param {String|SqlBuilder} pTable - * @param {String|String[]|SqlBuilder} pCondition The where condition. This can be - * a string (without the where keyword), a SqlBuilder or an array (for prepared queries). - * @param {String} [pTableAlias] table alias + * + * @param {String|SqlBuilder} pTable if it is a String, it is used as it is as table<br/> + * if it is a SqlBuilder, it is used as subselect: e.g. select * from Table1 join (select FIRSTNAME from PERSON) on ... + * @param {String|SqlBuilder} [pCondition] The where condition. This can be<br/> + * - a string (without the where keyword)<br/> + * - a SqlBuilder NOTE: only the condition is used from it + * + * @param {String} [pTableAlias] This alias is used to add an alias to the tablename * @return {SqlBuilder} current SqlBuilder object */ SqlBuilder.prototype.rightJoin = function(pTable, pCondition, pTableAlias) @@ -329,32 +346,121 @@ SqlBuilder.prototype.rightJoin = function(pTable, pCondition, pTableAlias) } /** - * Sets the where clause of the sql. + * Throws an error if pValue is null, undefined or a SqlBuilder without condition (or if pValue is a $-variable: error if the result of it is null or undefined)<br/> + * Also throws an error if pFieldOrCond is the only parameter and it is null<br/> + * <br/> + * Starts the where clause of the SQL. You may pass the first condition with it.<br/> + * But you can also call this function without any parameter and add the conditions with subsequent .and / .or<br/> + * <br/> + * This method exists mainly for semantic reasons and can only be callled once.<br/> + * As shourtcut you could use the newWhere(...) function.<br/> * - * @param {String|String[]|SqlCondition} pCondition The where condition. This can be - * a string (without the where keyword), a SqlCondition or an array (for prepared queries). - * + * @param {String|String[]|SqlBuilder|PreparedSqlArray|null} [pFieldOrCond] If this is the only parameter, it is used as Condition <br/> + * else it is used as Field.<br/> + * <br/> + * If you use it as Subselect (the only param), it can be:<br/> + * - a string: just added as it is<br/> + * - a PreparedSqlArray: an Array in this form: [sqlStr, [[value1, type1], [valueN, typeN]]]<br/> + * the sql is just used as it is.<br/> + * - a SqlBuilder: ONLY THE CONDITION is used from it<br/> + * <br/> + * If you use it as a Field (at least pValue has to be filled), this param provides the field information to<br/> + * load the SQLTYPE for this condition. <br/> + * It can be provided in the following ways:<br/> + * - a string: ONLY in this form: "TABLENAME.COLUMNNAME" <br/> + * Note1: you may have problems with names containing a '.' Use the next variant (as array) in this case<br/> + * Note2: if you need a table alias use the next variant (as array)<br/> + * - a array: ["TABLENAME", "COLUMNNAME", "tableAlias"] OR ["TABLENAME", "COLUMNNAME"]<br/> + * Note: this can also be null if you don't need the field and use a pCondition without a # + * + * @param {String|SqlBuilder|PreparedSqlArray|Array|OtherTypes} [pValue] This is the value which is used for the condition.<br/> + * Basically it can be nearly everything you need.<br/> + * - String, etc: is just used as value for the prepared statement. Of course it has to fit the type of the db-column<br/> + * - String starting with '$' is treated as jdito-variable: is loaded with vars.getString("$..."). <br/> + * Note: Use 2 '$' to escape the $ if you don't want it to be treated as JditoVar + * + * @param {String} [pCondition="# = ?"] This is the condition which should be used to compare the field with the value.<br/> + * # will be replaced by the field (pFieldOrCond) If pFieldOrCond is null, you can ommit #<br/> + * ? will be replaced by pValue + * + * @param {SQLTYPES|Numeric} [pFieldType=AutomaticallyLoadedType] You can specify which datatype should be used for the prepared statement <br/> + * In most cases you don't need this.<br/> + * This is helpful if you for example have a pCondition "year(#) = ?"<br/> + * then the db-field is DATETIME, but the value is INTEGER. In this case you can overwrite the type. + * * @return {SqlBuilder} current SqlBuilder object */ -SqlBuilder.prototype.where = function(pFieldOrCond, pValue, pCond, pFieldType) +SqlBuilder.prototype.where = function(pFieldOrCond, pValue, pCondition, pFieldType) { - return this._setWhere(pFieldOrCond, pValue, pCond, pFieldType, this.or); + return this._setWhere(pFieldOrCond, pValue, pCondition, pFieldType, this.or); } -SqlBuilder.prototype.whereIfSet = function(pFieldOrCond, pValue, pCond, pFieldType) +/** + * Difference to where(): where throws errors on invalid values, whereIfSet just ignores the condition and does nothing (usefull e.g. for the parameter variables ("$param.ddd") in conditionProcesses.)<br/> + * <br/> + * Starts the whereIfSet clause of the SQL. You may pass the first condition with it.<br/> + * But you can also call this function without any parameter and add the conditions with subsequent .and / .or<br/> + * <br/> + * This method exists mainly for semantic reasons and can only be callled once.<br/> + * As shourtcut you could use the newWhereIfSet(...) function. + * + * @param {String|String[]|SqlBuilder|PreparedSqlArray|null} [pFieldOrCond] If this is the only parameter, it is used as Condition <br/> + * else it is used as Field.<br/> + * <br/> + * If you use it as Subselect (the only param), it can be:<br/> + * - a string: just added as it is<br/> + * - a PreparedSqlArray: an Array in this form: [sqlStr, [[value1, type1], [valueN, typeN]]]<br/> + * the sql is just used as it is.<br/> + * - a SqlBuilder: ONLY THE CONDITION is used from it<br/> + * <br/> + * If you use it as a Field (at least pValue has to be filled), this param provides the field information to<br/> + * load the SQLTYPE for this condition. <br/> + * It can be provided in the following ways:<br/> + * - a string: ONLY in this form: "TABLENAME.COLUMNNAME" <br/> + * Note1: you may have problems with names containing a '.' Use the next variant (as array) in this case<br/> + * Note2: if you need a table alias use the next variant (as array)<br/> + * - a array: ["TABLENAME", "COLUMNNAME", "tableAlias"] OR ["TABLENAME", "COLUMNNAME"]<br/> + * Note: this can also be null if you don't need the field and use a pCondition without a #<br/> + * + * @param {String|SqlBuilder|PreparedSqlArray|Array|OtherTypes} [pValue] This is the value which is used for the condition.<br/> + * Basically it can be nearly everything you need.<br/> + * - String, etc: is just used as value for the prepared statement. Of course it has to fit the type of the db-column<br/> + * - String starting with '$' is treated as jdito-variable: is loaded with vars.getString("$..."). <br/> + * Note: Use 2 '$' to escape the $ if you don't want it to be treated as JditoVar + * + * @param {String} [pCondition="# = ?"] This is the condition which should be used to compare the field with the value.<br/> + * # will be replaced by the field (pFieldOrCond) If pFieldOrCond is null, you can ommit #<br/> + * ? will be replaced by pValue<br/> + * + * @param {SQLTYPES|Numeric} [pFieldType=AutomaticallyLoadedType] You can specify which datatype should be used for the prepared statement <br/> + * In most cases you don't need this.<br/> + * This is helpful if you for example have a pCondition "year(#) = ?"<br/> + * then the db-field is DATETIME, but the value is INTEGER. In this case you can overwrite the type. + * + * @return {SqlBuilder} current SqlBuilder object + */ +SqlBuilder.prototype.whereIfSet = function(pFieldOrCond, pValue, pCondition, pFieldType) { - return this._setWhere(pFieldOrCond, pValue, pCond, pFieldType, this.orIfSet); + return this._setWhere(pFieldOrCond, pValue, pCondition, pFieldType, this.orIfSet); } /** - * helper function for .where and .whereIfSet because they do almost the same + * helper function for .where and .whereIfSet because they do almost the same<br/> + * See .where() for further explanations + * + * @param {String|String[]|SqlBuilder|PreparedSqlArray|null} [pFieldOrCond] + * @param {String|SqlBuilder|PreparedSqlArray|Array|OtherTypes} [pValue] + * @param {String} [pCondition="# = ?"] + * @param {SQLTYPES|Numeric} [pFieldType=AutomaticallyLoadedType] + * @param {SQLTYPES|Numeric} pAddCondFn=AutomaticallyLoadedType This is a callback which is called if a condition should be added (needs to have same parameters as .or() * - * @private + * @return {SqlBuilder} current SqlBuilder object + * @ignore */ -SqlBuilder.prototype._setWhere = function (pFieldOrCond, pValue, pCond, pFieldType, pAddCondFn) +SqlBuilder.prototype._setWhere = function (pFieldOrCond, pValue, pCondition, pFieldType, pAddCondFn) { // allow where-call without parameter to just enable where mode - if (pFieldOrCond === undefined && pValue === undefined && pCond === undefined && pFieldType === undefined) + if (pFieldOrCond === undefined && pValue === undefined && pCondition === undefined && pFieldType === undefined) { this._where._whereWasCalled = true; return this; @@ -369,12 +475,19 @@ SqlBuilder.prototype._setWhere = function (pFieldOrCond, pValue, pCond, pFieldTy throw SqlBuilder.ERROR_ONLY_ONE_WHERE(); this._where._whereWasCalled = true; - return pAddCondFn.call(this, pFieldOrCond, pValue, pCond, pFieldType); + return pAddCondFn.call(this, pFieldOrCond, pValue, pCondition, pFieldType); } /** + * helper function which adds a condition + * + * @param {String|SqlBuilder|PreparedSqlArray} pCondition the condition to add + * @param {Boolean} [pMandatory=true] if true: throws error on SqlBuilder without conditon or PreparedSqlArray with empty string. Else: just does nothing + * @param {CallbackFunction} pAddPreparedConditionCallback A Callback funtion which receives a PreparedSqlArray as parameter + * @param {Boolean} pBrackets if true, Brackets are added in some cases * - * @private + * @return {SqlBuilder} current SqlBuilder object + * @ignore */ SqlBuilder.prototype._whereCondition = function(pCondition, pMandatory, pAddPreparedConditionCallback, pBrackets) { @@ -440,7 +553,15 @@ SqlBuilder.prototype._whereCondition = function(pCondition, pMandatory, pAddPrep } /** - * @private + * helper function which adds a Subquery-condition + * + * @param {SqlBuilder|PreparedSqlArray} pSubquery the subquery to add + * @param {Boolean} [pMandatory=true] if true: throws error on SqlBuilder without conditon or PreparedSqlArray with empty string. Else: just does nothing + * @param {Boolean} pCondition the condition to be used: e.g. "exists(?)" the ? is replaced by the subquery + * @param {CallbackFunction} pAddPreparedConditionCallback A Callback funtion which receives a PreparedSqlArray as parameter + * + * @return {SqlBuilder} current SqlBuilder object + * @ignore */ SqlBuilder.prototype._whereSubquery = function(pSubquery, pMandatory, pCondition, pAddPreparedConditionCallback) { @@ -488,29 +609,27 @@ SqlBuilder.prototype._whereSubquery = function(pSubquery, pMandatory, pCondition } /** - * @param {String | String[]} pFieldOrCond the database field as "tablename.columnname"; e.g. "ORGANISATION.NAME" or as array with column-alias: ["ORGANISATION", "NAME", "myorgAlias"] - * @param {String} pValue the value that shall be set into the prepared statement - * @param {Boolean} [pMandatory=true] if true: throw error if pValue is null, undefined, "" or an empty jdito-variable - * @param {String} [pCond="# = ?"] the strucutre of the SQL condition as preparedString, you can use a number sign "#" as placeholder for you fieldname; - * e.g. "# > ?"; escaping the number sign is possible with a backslash "\" - * @param {Numeric | Boolean} [pFieldType] SQL-column-type; if the fieldType is not given it's loaded automatically; - * The loaded type is cached if no type is given. So it is also safe to use this in a loop. - * e.g. - * for (...) { - * cond.andPrepare("SALESPROJECT_CLASSIFICATION.TYPE", entry, "# <> ?") - * } + * helper function which adds a condition to the where + * + * @param {String|String[]|SqlBuilder|PreparedSqlArray|null} pFieldOrCond see .where() + * @param {String|SqlBuilder|PreparedSqlArray|Array|OtherTypes} pValue see .where() + * @param {Boolean} [pMandatory=true] if true: throw error if pValue is null, undefined, SqlBuilder without condition, etc... else just ignore the condition + * @param {String} [pCondition="# = ?"] see .where() + * @param {SQLTYPES|Numeric} [pFieldType=AutomaticallyLoadedType] see .where() + * @param {CallbackFunction} pAddPreparedConditionCallback A Callback funtion which receives a PreparedSqlArray as parameter + * * @return {SqlBuilder} current SqlBuilder object - * @private + * @ignore */ -SqlBuilder.prototype._addWhere = function(pFieldOrCond, pValue, pMandatory, pCond, pFieldType, pAddPreparedConditionCallback) +SqlBuilder.prototype._addWhere = function(pFieldOrCond, pValue, pMandatory, pCondition, pFieldType, pAddPreparedConditionCallback) { if (!this._where._whereWasCalled) throw SqlBuilder.ERROR_WHERE_NOT_FIRST(); - if (!pMandatory && pFieldOrCond === undefined && pValue === undefined && pCond === undefined && pFieldType === undefined) + if (!pMandatory && pFieldOrCond === undefined && pValue === undefined && pCondition === undefined && pFieldType === undefined) return this; - if (pFieldOrCond === undefined && pValue === undefined && pCond === undefined && pFieldType === undefined) + if (pFieldOrCond === undefined && pValue === undefined && pCondition === undefined && pFieldType === undefined) throw SqlBuilder.ERROR_NO_PARAMETER_PROVIDED(); // Special case: if only pFieldOrCond is set and we can identify it as a valid field-string (e.g. "Table.Field") we assume that it is not just a condition string. @@ -518,7 +637,7 @@ SqlBuilder.prototype._addWhere = function(pFieldOrCond, pValue, pMandatory, pCon // --> this only works if isFullFieldQualifier() can detect if the supplied string is a valid field-string or if it is some sql. // currently it checks for some special characters which should not exist in any field-string but in conditions. // If there is a special case missing -> add it to the regexp in isFullFieldQualifier() - if (pValue === undefined && pCond === undefined && pFieldType === undefined && typeof pFieldOrCond == "string" && SqlUtils.isFullFieldQualifier(pFieldOrCond)) + if (pValue === undefined && pCondition === undefined && pFieldType === undefined && typeof pFieldOrCond == "string" && SqlUtils.isFullFieldQualifier(pFieldOrCond)) { if (pMandatory) throw SqlBuilder.ERROR_VALUE_IS_MANDATORY(); @@ -530,7 +649,7 @@ SqlBuilder.prototype._addWhere = function(pFieldOrCond, pValue, pMandatory, pCon pMandatory = true; // just call the andCondition function if it is only a Condition - if (pFieldOrCond !== undefined && pValue === undefined && pCond === undefined && pFieldType === undefined) + if (pFieldOrCond !== undefined && pValue === undefined && pCondition === undefined && pFieldType === undefined) return this._whereCondition(pFieldOrCond, pMandatory, pAddPreparedConditionCallback, true); // first check the default-mandatory-cases: null or undefined. everything else such as checking $-variables is done later @@ -538,8 +657,8 @@ SqlBuilder.prototype._addWhere = function(pFieldOrCond, pValue, pMandatory, pCon throw SqlBuilder.ERROR_VALUE_IS_MANDATORY(); // a field is string or array -> normal case - // OR !pFieldOrCond and pValue and pCond is given -> preparedSQL/SqlBuilder can be used without field if pCond is set - if((typeof pFieldOrCond == "string" || Array.isArray(pFieldOrCond)) || (!pFieldOrCond && (pCond && pValue instanceof SqlBuilder || !(pValue instanceof SqlBuilder)))) + // OR !pFieldOrCond and pValue and pCondition is given -> preparedSQL/SqlBuilder can be used without field if pCondition is set + if((typeof pFieldOrCond == "string" || Array.isArray(pFieldOrCond)) || (!pFieldOrCond && (pCondition && pValue instanceof SqlBuilder || !(pValue instanceof SqlBuilder)))) { var field = pFieldOrCond; var typeofValue = typeof pValue; @@ -548,7 +667,7 @@ SqlBuilder.prototype._addWhere = function(pFieldOrCond, pValue, pMandatory, pCon // ... a SqlBuilder / Prepared statement array -> it is a SqlBuilder containing a complete subquery or an simple array (in statement) if (pValue instanceof SqlBuilder || Array.isArray(pValue) || (typeofValue == "string" && (pFieldOrCond == undefined || pFieldOrCond == null))) { - // check if the array is really a prepared statement or just a value-array for an in + // check if the array is really a value-array for an in and not a prepared statement if (Array.isArray(pValue) && (pValue.lenght <= 1 || !Array.isArray(pValue[1]))) { if (pValue.length == 0) @@ -559,8 +678,8 @@ SqlBuilder.prototype._addWhere = function(pFieldOrCond, pValue, pMandatory, pCon return this; } - if (!pCond) - pCond = "# in ?"; + if (!pCondition) + pCondition = "# in ?"; if (field != null) { @@ -570,50 +689,53 @@ SqlBuilder.prototype._addWhere = function(pFieldOrCond, pValue, pMandatory, pCon } // value-array -> convert it to a prepared statement ["(?, ?, ?)", [[val1, type1], [val2, type2], [val3, type3]]] - this._whereCondition(this._prepare(field, SqlUtils.getSqlInStatement(undefined, pValue, undefined, true, pFieldType), pCond, pFieldType, false), undefined, pAddPreparedConditionCallback, true); + this._whereCondition(this._prepare(field, SqlUtils.getSqlInStatement(undefined, pValue, undefined, true, pFieldType), pCondition, pFieldType, false), undefined, pAddPreparedConditionCallback, true); return this; } if (pFieldOrCond !== null && pFieldOrCond !== undefined) { - if (!pCond) - pCond = "# = ?" + if (!pCondition) + pCondition = "# = ?" - pCond = SqlUtils.replaceConditionTemplate(pCond, '#', SqlUtils.parseField(pFieldOrCond)[0]) + pCondition = SqlUtils.replaceConditionTemplate(pCondition, '#', SqlUtils.parseField(pFieldOrCond)[0]) } else { - if (!pCond) - pCond = "?" + if (!pCondition) + pCondition = "?" } - return this._whereSubquery(pValue, pMandatory, pCond, pAddPreparedConditionCallback); + // _whereSubquery can handle SqlBuilder and prepared statements as value + return this._whereSubquery(pValue, pMandatory, pCondition, pAddPreparedConditionCallback); } - if (!pCond) - pCond = "# = ?" + if (!pCondition) + pCondition = "# = ?" // ... a string starting with $ -> jdito varable which has to be resolved - //TODO: this could be not wanted in some cases, what if you want to search for '$'? --> posibility to eycape with a second $ - if (typeofValue == "string" && pValue[0] == "$") + if (typeofValue == "string" && pValue.length >= 2 && pValue[0] == "$" && pValue[1] != "$") // escape $ if using two $ { pValue = vars.getString(pValue) if (pMandatory && pValue === null) throw SqlBuilder.ERROR_VALUE_IS_MANDATORY_JDITO_VAR(); if (pValue == "" || pValue) - this._whereCondition(this._prepare(field, pValue, pCond, pFieldType), undefined, pAddPreparedConditionCallback); + this._whereCondition(this._prepare(field, pValue, pCondition, pFieldType), undefined, pAddPreparedConditionCallback); return this; } + + // remove the first $ if there are two $ + if (typeofValue == "string" && pValue.length >= 2 && pValue[0] == "$" && pValue[1] == "$") + pValue = pValue.slice(1); // ... everything else -> just pass it if (pValue === false || pValue === 0 || pValue === "" || pValue) { - this._whereCondition(this._prepare(field, pValue, pCond, pFieldType), undefined, pAddPreparedConditionCallback); + this._whereCondition(this._prepare(field, pValue, pCondition, pFieldType), undefined, pAddPreparedConditionCallback); } - return this; } @@ -621,13 +743,21 @@ SqlBuilder.prototype._addWhere = function(pFieldOrCond, pValue, pMandatory, pCon } /** - * @private + * helper function to add a condition via "and" + * + * @param {String|String[]|SqlBuilder|PreparedSqlArray|null} pFieldOrCond see .where() + * @param {String|SqlBuilder|PreparedSqlArray|Array|OtherTypes} pValue see .where() + * @param {Boolean} [pMandatory=true] if true: throw error if pValue is null, undefined, SqlBuilder without condition, etc... else just ignore the condition + * @param {String} [pCondition="# = ?"] see .where() + * @param {SQLTYPES|Numeric} [pFieldType=AutomaticallyLoadedType] see .where() + * + * @ignore */ -SqlBuilder.prototype._and = function(pFieldOrCond, pValue, pMandatory, pCond, pFieldType) +SqlBuilder.prototype._and = function(pFieldOrCond, pValue, pMandatory, pCondition, pFieldType) { var that = this; - return this._addWhere(pFieldOrCond, pValue, pMandatory, pCond, pFieldType, function(pPreparedCondition) + return this._addWhere(pFieldOrCond, pValue, pMandatory, pCondition, pFieldType, function(pPreparedCondition) { that._where._previouslyOnlyOr = false; if (pPreparedCondition.length == 2 && typeof pPreparedCondition[0] == "string" && pPreparedCondition[0] != "" && Array.isArray(pPreparedCondition[1])) @@ -642,13 +772,22 @@ SqlBuilder.prototype._and = function(pFieldOrCond, pValue, pMandatory, pCond, pF } /** - * @private + * helper function to add a condition via "or" + * The callback inside of this function adds brackets where needed. + * + * @param {String|String[]|SqlBuilder|PreparedSqlArray|null} pFieldOrCond see .where() + * @param {String|SqlBuilder|PreparedSqlArray|Array|OtherTypes} pValue see .where() + * @param {Boolean} [pMandatory=true] if true: throw error if pValue is null, undefined, SqlBuilder without condition, etc... else just ignore the condition + * @param {String} [pCondition="# = ?"] see .where() + * @param {SQLTYPES|Numeric} [pFieldType=AutomaticallyLoadedType] see .where() + * + * @ignore */ -SqlBuilder.prototype._or = function(pFieldOrCond, pValue, pMandatory, pCond, pFieldType) +SqlBuilder.prototype._or = function(pFieldOrCond, pValue, pMandatory, pCondition, pFieldType) { var that = this; - return this._addWhere(pFieldOrCond, pValue, pMandatory, pCond, pFieldType, function(pPreparedCondition, pAlreadySurroundedByBrackets) + return this._addWhere(pFieldOrCond, pValue, pMandatory, pCondition, pFieldType, function(pPreparedCondition, pAlreadySurroundedByBrackets) { if (pPreparedCondition.length == 2 && typeof pPreparedCondition[0] == "string" && pPreparedCondition[0] != "" && Array.isArray(pPreparedCondition[1])) { @@ -683,87 +822,248 @@ SqlBuilder.prototype._or = function(pFieldOrCond, pValue, pMandatory, pCond, pFi }); } +/** + * Constant-like function which provides a value for pCondition if you need a "not in" statement. + * + * @return {String} + * + * @example + * var cond = newWhere("PERSON.FIRSTNAME", "Fritz", SqlBuilder.NOT_IN()) + */ SqlBuilder.NOT_IN = function() { return "# not in ?"; } +/** + * Constant-like function which provides a value for pCondition if you need a "in" statement. + * + * @return {String} + * + * @example + * var cond = newWhere("PERSON.FIRSTNAME", "Fritz", SqlBuilder.IN()) + */ SqlBuilder.IN = function() { return "# in ?"; } +/** + * Constant-like function which provides a value for pCondition if you need a "exists" statement. + * + * @return {String} + * + * @example + * var cond = newWhere("PERSON.FIRSTNAME", "Fritz", SqlBuilder.EXISTS()) + */ SqlBuilder.EXISTS = function() { return "exists ?"; } +/** + * Constant-like function which provides a value for pCondition if you need a "not exists" statement. + * + * @return {String} + * + * @example + * var cond = newWhere("PERSON.FIRSTNAME", "Fritz", SqlBuilder.NOT_EXISTS()) + */ SqlBuilder.NOT_EXISTS = function() { return "exists ?"; } -//TODO: more detailed comments with examples - /** - * appends a condition with or + * Throws an error if pValue is null, undefined or a SqlBuilder without condition (or if pValue is a $-variable: error if the result of it is null or undefined)<br/> + * Also throws an error if pFieldOrCond is the only parameter and it is null<br/> + * <br/> + * Adds a condition by using "or" to the Sql.<br/> + * Note: You have to call .where before using .and / .or (this is mainly for semantic reasons) * - * @param {String|SqlBuilder} pFieldOrCond - * @param {String|String[]|SqlBuilder} pValue - * @param {String} pCond - * @param {Number} pFieldType - * @return {SqlBuilder} the current SqlBuilder object + * @param {String|String[]|SqlBuilder|PreparedSqlArray|null} [pFieldOrCond] If this is the only parameter, it is used as Condition <br/> + * else it is used as Field.<br/> + * <br/> + * If you use it as Subselect (the only param), it can be:<br/> + * - a string: just added as it is<br/> + * - a PreparedSqlArray: an Array in this form: [sqlStr, [[value1, type1], [valueN, typeN]]]<br/> + * the sql is just used as it is.<br/> + * - a SqlBuilder: ONLY THE CONDITION is used from it<br/> + * <br/> + * If you use it as a Field (at least pValue has to be filled), this param provides the field information to<br/> + * load the SQLTYPE for this condition. <br/> + * It can be provided in the following ways:<br/> + * - a string: ONLY in this form: "TABLENAME.COLUMNNAME" <br/> + * Note1: you may have problems with names containing a '.' Use the next variant (as array) in this case<br/> + * Note2: if you need a table alias use the next variant (as array)<br/> + * - a array: ["TABLENAME", "COLUMNNAME", "tableAlias"] OR ["TABLENAME", "COLUMNNAME"]<br/> + * Note: this can also be null if you don't need the field and use a pCondition without a # + * + * @param {String|SqlBuilder|PreparedSqlArray|Array|OtherTypes} [pValue] This is the value which is used for the condition.<br/> + * Basically it can be nearly everything you need.<br/> + * - String, etc: is just used as value for the prepared statement. Of course it has to fit the type of the db-column<br/> + * - String starting with '$' is treated as jdito-variable: is loaded with vars.getString("$..."). <br/> + * Note: Use 2 '$' to escape the $ if you don't want it to be treated as JditoVar + * + * @param {String} [pCondition="# = ?"] This is the condition which should be used to compare the field with the value.<br/> + * # will be replaced by the field (pFieldOrCond) If pFieldOrCond is null, you can ommit #<br/> + * ? will be replaced by pValue + * + * @param {SQLTYPES|Numeric} [pFieldType=AutomaticallyLoadedType] You can specify which datatype should be used for the prepared statement <br/> + * In most cases you don't need this.<br/> + * This is helpful if you for example have a pCondition "year(#) = ?"<br/> + * then the db-field is DATETIME, but the value is INTEGER. In this case you can overwrite the type. + * + * @return {SqlBuilder} current SqlBuilder object */ -SqlBuilder.prototype.or = function(pFieldOrCond, pValue, pCond, pFieldType) +SqlBuilder.prototype.or = function(pFieldOrCond, pValue, pCondition, pFieldType) { - return this._or(pFieldOrCond, pValue, true, pCond, pFieldType); + return this._or(pFieldOrCond, pValue, true, pCondition, pFieldType); } /** - * appends a condition with or if a value is provided + * Difference to or(): or() throws errors on invalid values, orIfSet just ignores the condition and does nothing (usefull e.g. for the parameter variables ("$param.ddd") in conditionProcesses.)<br/> + * <br/> + * Adds a condition by using "or" to the Sql.<br/> + * Note: You have to call .where before using .and / .or (this is mainly for semantic reasons) * - * @param {String|SqlBuilder} pFieldOrCond - * @param {String|String[]|SqlBuilder} pValue - * @param {String} pCond - * @param {Number} pFieldType - * @return {SqlBuilder} the current SqlBuilder object + * @param {String|String[]|SqlBuilder|PreparedSqlArray|null} [pFieldOrCond] If this is the only parameter, it is used as Condition <br/> + * else it is used as Field.<br/> + * <br/> + * If you use it as Subselect (the only param), it can be:<br/> + * - a string: just added as it is<br/> + * - a PreparedSqlArray: an Array in this form: [sqlStr, [[value1, type1], [valueN, typeN]]]<br/> + * the sql is just used as it is.<br/> + * - a SqlBuilder: ONLY THE CONDITION is used from it<br/> + * <br/> + * If you use it as a Field (at least pValue has to be filled), this param provides the field information to<br/> + * load the SQLTYPE for this condition. <br/> + * It can be provided in the following ways:<br/> + * - a string: ONLY in this form: "TABLENAME.COLUMNNAME" <br/> + * Note1: you may have problems with names containing a '.' Use the next variant (as array) in this case<br/> + * Note2: if you need a table alias use the next variant (as array)<br/> + * - a array: ["TABLENAME", "COLUMNNAME", "tableAlias"] OR ["TABLENAME", "COLUMNNAME"]<br/> + * Note: this can also be null if you don't need the field and use a pCondition without a # + * + * @param {String|SqlBuilder|PreparedSqlArray|Array|OtherTypes} [pValue] This is the value which is used for the condition.<br/> + * Basically it can be nearly everything you need.<br/> + * - String, etc: is just used as value for the prepared statement. Of course it has to fit the type of the db-column<br/> + * - String starting with '$' is treated as jdito-variable: is loaded with vars.getString("$..."). <br/> + * Note: Use 2 '$' to escape the $ if you don't want it to be treated as JditoVar + * + * @param {String} [pCondition="# = ?"] This is the condition which should be used to compare the field with the value.<br/> + * # will be replaced by the field (pFieldOrCond) If pFieldOrCond is null, you can ommit #<br/> + * ? will be replaced by pValue + * + * @param {SQLTYPES|Numeric} [pFieldType=AutomaticallyLoadedType] You can specify which datatype should be used for the prepared statement <br/> + * In most cases you don't need this.<br/> + * This is helpful if you for example have a pCondition "year(#) = ?"<br/> + * then the db-field is DATETIME, but the value is INTEGER. In this case you can overwrite the type. + * + * @return {SqlBuilder} current SqlBuilder object */ -SqlBuilder.prototype.orIfSet = function(pFieldOrCond, pValue, pCond, pFieldType) +SqlBuilder.prototype.orIfSet = function(pFieldOrCond, pValue, pCondition, pFieldType) { - return this._or(pFieldOrCond, pValue, false, pCond, pFieldType); + return this._or(pFieldOrCond, pValue, false, pCondition, pFieldType); } /** - * appends a condition with and + * Throws an error if pValue is null, undefined or a SqlBuilder without condition (or if pValue is a $-variable: error if the result of it is null or undefined)<br/> + * Also throws an error if pFieldOrCond is the only parameter and it is null<br/> + * <br/> + * Adds a condition by using "and" to the Sql.<br/> + * Note: You have to call .where before using .and / .or (this is mainly for semantic reasons) * - * @param {String|SqlBuilder} pFieldOrCond - * @param {String|String[]|SqlBuilder} pValue - * @param {String} pCond - * @param {Number} pFieldType - * @return {SqlBuilder} the current SqlBuilder object + * @param {String|String[]|SqlBuilder|PreparedSqlArray|null} [pFieldOrCond] If this is the only parameter, it is used as Condition <br/> + * else it is used as Field.<br/> + * <br/> + * If you use it as Subselect (the only param), it can be:<br/> + * - a string: just added as it is<br/> + * - a PreparedSqlArray: an Array in this form: [sqlStr, [[value1, type1], [valueN, typeN]]]<br/> + * the sql is just used as it is.<br/> + * - a SqlBuilder: ONLY THE CONDITION is used from it<br/> + * <br/> + * If you use it as a Field (at least pValue has to be filled), this param provides the field information to<br/> + * load the SQLTYPE for this condition. <br/> + * It can be provided in the following ways:<br/> + * - a string: ONLY in this form: "TABLENAME.COLUMNNAME" <br/> + * Note1: you may have problems with names containing a '.' Use the next variant (as array) in this case<br/> + * Note2: if you need a table alias use the next variant (as array)<br/> + * - a array: ["TABLENAME", "COLUMNNAME", "tableAlias"] OR ["TABLENAME", "COLUMNNAME"]<br/> + * Note: this can also be null if you don't need the field and use a pCondition without a # + * + * @param {String|SqlBuilder|PreparedSqlArray|Array|OtherTypes} [pValue] This is the value which is used for the condition.<br/> + * Basically it can be nearly everything you need.<br/> + * - String, etc: is just used as value for the prepared statement. Of course it has to fit the type of the db-column<br/> + * - String starting with '$' is treated as jdito-variable: is loaded with vars.getString("$..."). <br/> + * Note: Use 2 '$' to escape the $ if you don't want it to be treated as JditoVar + * + * @param {String} [pCondition="# = ?"] This is the condition which should be used to compare the field with the value.<br/> + * # will be replaced by the field (pFieldOrCond) If pFieldOrCond is null, you can ommit #<br/> + * ? will be replaced by pValue + * + * @param {SQLTYPES|Numeric} [pFieldType=AutomaticallyLoadedType] You can specify which datatype should be used for the prepared statement <br/> + * In most cases you don't need this.<br/> + * This is helpful if you for example have a pCondition "year(#) = ?"<br/> + * then the db-field is DATETIME, but the value is INTEGER. In this case you can overwrite the type. + * + * @return {SqlBuilder} current SqlBuilder object */ -SqlBuilder.prototype.and = function(pFieldOrCond, pValue, pCond, pFieldType) +SqlBuilder.prototype.and = function(pFieldOrCond, pValue, pCondition, pFieldType) { - return this._and(pFieldOrCond, pValue, true, pCond, pFieldType); + return this._and(pFieldOrCond, pValue, true, pCondition, pFieldType); } /** - * appends a condition with and if a value is provided + * Difference to and(): and() throws errors on invalid values, andIfSet just ignores the condition and does nothing (usefull e.g. for the parameter variables ("$param.ddd") in conditionProcesses.)<br/> + * <br/> + * Adds a condition by using "and" to the Sql.<br/> + * Note: You have to call .where before using .and / .or (this is mainly for semantic reasons) * - * @param {String|SqlBuilder} pFieldOrCond - * @param {String|String[]|SqlBuilder} pValue - * @param {String} pCond - * @param {Number} pFieldType - * @return {SqlBuilder} the current SqlBuilder object + * @param {String|String[]|SqlBuilder|PreparedSqlArray|null} [pFieldOrCond] If this is the only parameter, it is used as Condition <br/> + * else it is used as Field.<br/> + * <br/> + * If you use it as Subselect (the only param), it can be:<br/> + * - a string: just added as it is<br/> + * - a PreparedSqlArray: an Array in this form: [sqlStr, [[value1, type1], [valueN, typeN]]]<br/> + * the sql is just used as it is.<br/> + * - a SqlBuilder: ONLY THE CONDITION is used from it<br/> + * <br/> + * If you use it as a Field (at least pValue has to be filled), this param provides the field information to<br/> + * load the SQLTYPE for this condition. <br/> + * It can be provided in the following ways:<br/> + * - a string: ONLY in this form: "TABLENAME.COLUMNNAME" <br/> + * Note1: you may have problems with names containing a '.' Use the next variant (as array) in this case<br/> + * Note2: if you need a table alias use the next variant (as array)<br/> + * - a array: ["TABLENAME", "COLUMNNAME", "tableAlias"] OR ["TABLENAME", "COLUMNNAME"]<br/> + * Note: this can also be null if you don't need the field and use a pCondition without a # + * + * @param {String|SqlBuilder|PreparedSqlArray|Array|OtherTypes} [pValue] This is the value which is used for the condition.<br/> + * Basically it can be nearly everything you need.<br/> + * - String, etc: is just used as value for the prepared statement. Of course it has to fit the type of the db-column<br/> + * - String starting with '$' is treated as jdito-variable: is loaded with vars.getString("$..."). <br/> + * Note: Use 2 '$' to escape the $ if you don't want it to be treated as JditoVar + * + * @param {String} [pCondition="# = ?"] This is the condition which should be used to compare the field with the value.<br/> + * # will be replaced by the field (pFieldOrCond) If pFieldOrCond is null, you can ommit #<br/> + * ? will be replaced by pValue + * + * @param {SQLTYPES|Numeric} [pFieldType=AutomaticallyLoadedType] You can specify which datatype should be used for the prepared statement <br/> + * In most cases you don't need this.<br/> + * This is helpful if you for example have a pCondition "year(#) = ?"<br/> + * then the db-field is DATETIME, but the value is INTEGER. In this case you can overwrite the type. + * + * @return {SqlBuilder} current SqlBuilder object */ -SqlBuilder.prototype.andIfSet = function(pFieldOrCond, pValue, pCond, pFieldType) +SqlBuilder.prototype.andIfSet = function(pFieldOrCond, pValue, pCondition, pFieldType) { - return this._and(pFieldOrCond, pValue, false, pCond, pFieldType); + return this._and(pFieldOrCond, pValue, false, pCondition, pFieldType); } /** * Sets the order by clause of the sql. - * @param {String|String[]} pOrderBy + * + * @param {String|String[]} pOrderBy a string is added as it is, a array is concatenated by ', ' * @return {SqlBuilder} current SqlBuilder object */ SqlBuilder.prototype.orderBy = function(pOrderBy) @@ -774,7 +1074,8 @@ SqlBuilder.prototype.orderBy = function(pOrderBy) /** * Sets the group by clause of the sql. - * @param {String|String[]} pFields + * + * @param {String|String[]} pFields a string is added as it is, a array is concatenated by ', ' * @return {SqlBuilder} current SqlBuilder object */ SqlBuilder.prototype.groupBy = function(pFields) @@ -785,6 +1086,7 @@ SqlBuilder.prototype.groupBy = function(pFields) /** * Adds another SqlBuilder object or select string with union. + * * @param {SqlBuilder|String} pSelect * @return {SqlBuilder} current SqlBuilder object */ @@ -796,6 +1098,7 @@ SqlBuilder.prototype.union = function(pSelect) /** * Adds another SqlBuilder object or select string with union all. + * * @param {SqlBuilder|String} pSelect * @return {SqlBuilder} current SqlBuilder object */ @@ -808,8 +1111,9 @@ SqlBuilder.prototype.unionAll = function(pSelect) /** * Adds a having clause to the sql. * - * @param {String|String[]|SqlBuilder} pCondition The where condition. This can be - * a string (without the where keyword), a SqlBuilder or an array (for prepared queries). + * @param {String|SqlBuilder} [pCondition] The having condition. This can be + * - a string (without the where keyword) + * - a SqlBuilder NOTE: only the condition is used from it * * @return {SqlBuilder} current SqlBuilder object */ @@ -831,7 +1135,8 @@ SqlBuilder.prototype.hasCondition = function() { /** * checks if conditions have been added to the object - * @return {Boolean} true if conditions have been added, false when not + * Note: this does not nessecarily mean that hasCondition() is true + * @return {Boolean} true if .where was already called */ SqlBuilder.prototype.whereWasCalled = function() { return this._where._whereWasCalled; @@ -839,7 +1144,8 @@ SqlBuilder.prototype.whereWasCalled = function() { /** * checks if all mandatory parts to execute the select have been added to the object - * @return {Boolean} true if select and from have been added, false when not + * ("select" and "from" parts) + * @return {Boolean} true if select and from have been added, false if not */ SqlBuilder.prototype.isFullSelect = function() { @@ -852,7 +1158,8 @@ SqlBuilder.prototype.isFullSelect = function() /** * function that resets the current where-condition as if no conditions would have been added * this is usefull if you want to reuse the same Builder over and over again with a different condition - * @return {null} + * + * @return {SqlBuilder} current SqlBuilder object */ SqlBuilder.prototype.clearWhere = function() { @@ -862,58 +1169,63 @@ SqlBuilder.prototype.clearWhere = function() } /** - * hidden function for composing preparedStatements - * @param {String | String[]} field the database field as "tablename.columnname"; e.g. "ORGANISATION.NAME" or as array with column-alias: ["ORGANISATION", "NAME", "myorgAlias"] - * @param {String} value the value that shall be set into the prepared statement - * @param {String} cond the strucutre of the SQL condition as preparedString, you can use a number sign "#" as placeholder for you fieldname; - * e.g. "# > ?"; escaping the number sign is possible with a backslash "\" + * helper function for composing preparedStatements <br/> + * <br/> + * see .where for more information about the parameters + * + * @param {String | String[]} pField the database field as "tablename.columnname"; e.g. "ORGANISATION.NAME" or as array with column-alias: ["ORGANISATION", "NAME", "myorgAlias"] + * @param {String} pValue the value that shall be set into the prepared statement + * @param {String} pCondition the strucutre of the SQL condition as preparedString, you can use a number sign "#" as placeholder for you fieldname; <br/> + * e.g. "# > ?"; escaping the number sign is possible with a backslash "\" <br/> * Default is "# = ?" - * @param {Numeric | Boolean} [fieldType] SQL-column-type; if the fieldType is not given it's loaded automatically; - * The loaded type is cached if no type is given. So it is also safe to use this in a loop. - * e.g. - * for (...) { - * cond.andPrepare("SALESPROJECT_CLASSIFICATION.TYPE", entry, "# <> ?") + * @param {Numeric | Boolean} [pFieldType] SQL-column-type; if the fieldType is not given it's loaded automatically; <br/> + * The loaded type is cached if no type is given. So it is also safe to use this in a loop. <br/> + * e.g. <br/> + * for (...) { <br/> + * cond.andPrepare("SALESPROJECT_CLASSIFICATION.TYPE", entry, "# <> ?") <br/> * } - * @return {String} the replaced SQL-condition string (replace # by the fieldname) - * @private + * @param {Boolean} pSubselectBrackets if true, brackets are added to subselects + * @return {PreparedSqlArray} a preparedSqlArray built out of the given parameters + * + * @ignore */ -SqlBuilder.prototype._prepare = function(field, value, cond, fieldType, pSubselectBrackets) +SqlBuilder.prototype._prepare = function(pField, pValue, pCondition, pFieldType, pSubselectBrackets) { if (pSubselectBrackets == undefined) pSubselectBrackets = true; - if (value == undefined) - throw new Error(translate.withArguments("${SQL_LIB_UNDEFINED_VALUE} field: %0", [field])); + if (pValue == undefined) + throw new Error(translate.withArguments("${SQL_LIB_UNDEFINED_VALUE} field: %0", [pField])); - if (cond == undefined) - cond = "# = ?"; + if (pCondition == undefined) + pCondition = "# = ?"; var alias; - if (field != null) + if (pField != null) { - [alias, field] = SqlUtils.parseField(field) - if (fieldType == undefined) - fieldType = SqlUtils.getSingleColumnType(field, undefined, this.alias); + [alias, field] = SqlUtils.parseField(pField) + if (pFieldType == undefined) + pFieldType = SqlUtils.getSingleColumnType(pField, undefined, this.alias); } var values = []; // If subselect: replace '?' with the subselect - if (Array.isArray(value)) + if (Array.isArray(pValue)) { - cond = SqlUtils.replaceConditionTemplate(cond, "\\?", (pSubselectBrackets ? " ( " : " ") + value[0] + (pSubselectBrackets ? " ) " : " ")); - values = value[1]; + pCondition = SqlUtils.replaceConditionTemplate(pCondition, "\\?", (pSubselectBrackets ? " ( " : " ") + pValue[0] + (pSubselectBrackets ? " ) " : " ")); + values = pValue[1]; } else { - var type = fieldType; - values = [[value.toString(), type]]; + var type = pFieldType; + values = [[pValue.toString(), type]]; } - if (field != null) - cond = SqlUtils.replaceConditionTemplate(cond, "#", alias); + if (pField != null) + pCondition = SqlUtils.replaceConditionTemplate(pCondition, "#", alias); - return [cond, values]; + return [pCondition, values]; } /** @@ -922,10 +1234,10 @@ SqlBuilder.prototype._prepare = function(field, value, cond, fieldType, pSubsele * @param {String|String[]|SqlBuilder} pElement the element to append * @param {String} [pPrefix] string to be added before pElement * @param {String} [pPostfix] string to be added after pElement - * @param {Boolean} [pAutoJoin] if this is true and pElement is an array, it will be automatically + * @param {Boolean} [pAutoJoin] if this is true and pElement is an array, it will be automatically <br/> * joined together to a string * - * @private + * @ignore */ SqlBuilder._getStatement = function (pElement, pPrefix, pPostfix, pAutoJoin) { @@ -934,12 +1246,13 @@ SqlBuilder._getStatement = function (pElement, pPrefix, pPostfix, pAutoJoin) { if (Array.isArray(pElement) && pElement.length !== undefined && pAutoJoin) //array of fields { - for (let i = 0, l = pElement.length; i < l; i++) + for (let i = 0; i < pElement.length; i++) { if (typeof pElement[i] !== "string") pElement[i] = _getElement(pElement[i]); } - pElement = pElement.join(", "); + + pElement = ArrayUtils.joinNonEmptyFields(pElement, ", "); } else { @@ -975,35 +1288,9 @@ SqlBuilder._getStatement = function (pElement, pPrefix, pPostfix, pAutoJoin) } /** - * concatenates two prepared statements - * - * @param {Array} pStatements array of prepared statements + * builds a prepared condition out of the object. Only the condition is used. Select, from, ... are ignored. * - * @return {Array} the resultung prepared statement - */ -SqlBuilder.concatPreparedStatements = function (pStatements) -{ - var sqlStr = ""; - var preparedVals = []; - for (let i = 0, l = pStatements.length; i < l; i++) - { - let part = pStatements[i]; - if (part && part.length) - { - if (sqlStr && part[0]) - sqlStr += " "; - sqlStr += part[0]; - if (part[1].length) - preparedVals = preparedVals.concat(part[1]); - } - } - return [sqlStr, preparedVals]; -} - -/** - * builds a prepared condition out of the object. Only the condition is used.Select, from, ... are ignored. - * - * @return {String[]} prepared condition + * @return {PreparedSqlArray} prepared condition */ SqlBuilder.prototype.buildCondition = function() { @@ -1011,9 +1298,10 @@ SqlBuilder.prototype.buildCondition = function() } /** - * builds a prepared statement out of the object + * builds a prepared statement out of the object. If a part doesn't exit, it's just ignored. * - * @return {String[]} prepared statement + * @param {String} [pDefaultConditionIfNone=""] a default condition string which should be used if the SqlBuilder doesn't have any condition + * @return {PreparedSqlArray} prepared statement */ SqlBuilder.prototype.build = function(pDefaultConditionIfNone) { @@ -1060,29 +1348,16 @@ SqlBuilder.prototype.build = function(pDefaultConditionIfNone) } /** - * translates SqlBuilder to plain SQL. Use this if prepared statements are not supported. - * For the db-functions (db.table, db.cell, etc.) use ".build()" as they support prepared statements. - * It resolves all prepared values. - * @param {String} [pAlias=undefined] the alias to use for db.translateStatement - * @return {String} plain SQL statement - * - * @deprecated use .toString() - */ -SqlBuilder.prototype.translate = function(pDefaultConditionIfNone) -{ - return this.toString(pDefaultConditionIfNone); -} - -/** - * Updates data in the database. + * Updates data in the database.<br/> + * Note: the default for pExecuteOnlyIfConditionExists is true to prevent updating all rows if the SqlBuilder has no condition. * - * @param {Boolean} [pExecuteOnlyIfConditionExists=true] If true, the update is only done if there is a condition. - * <strong>If this is set to false and there is no condition, every row in the table will be updated!</strong> - * @param {Array} pColumns - * @param {Array} [pColumnTypes] - * @param {Array} pValues - * @param {String} [pTableName] The table for updating data. If omitted, the from part of the SqlBuilder will be used. - * @param {Number} [pTimeout=-1] + * @param {Boolean} [pExecuteOnlyIfConditionExists=true] If true, the update is only done if there is a condition.<br/> + * <strong>IMPORTANT: If this is set to false and there is no condition, every row in the table will be updated!</strong> + * @param {String} [pTableName] The table for updating data. If undefined, the from part of the SqlBuilder will be used (works only if it is a tablename) + * @param {String[]} pColumns The columns where you want to update. + * @param {SQLTYPES[]} [pColumnTypes=null] normally you can set this to null as the types are calculated if not provided + * @param {String[]} pValues The values to be updated. + * @param {Number} [pTimeout=-1] * @return {Number} the number of rows affected * @throws {Error} if no table is provided */ @@ -1093,6 +1368,9 @@ SqlBuilder.prototype.updateData = function(pExecuteOnlyIfConditionExists, pTable if (!pTableName && !this._from) throw SqlBuilder.ERROR_NO_TABLE(); + if (!pColumns) + pColumns = null; + return db.updateData( (pTableName ? pTableName : this._tableName), pColumns, @@ -1107,11 +1385,12 @@ SqlBuilder.prototype.updateData = function(pExecuteOnlyIfConditionExists, pTable } /** - * Deletes data from the database. - * - * @param {Boolean} [pExecuteOnlyIfConditionExists=true] If true, the deletion is only done if there is a condition. - * <strong>If this is set to false and there is no condition, every row in the table will be deleted!</strong> - * @param {String} [pTableName] The table for deleting data. If omitted, the from part of the SqlBuilder will be used. + * Deletes data from the database.<br/> + * Note: the default for pExecuteOnlyIfConditionExists is true to prevent updating all rows if the SqlBuilder has no condition. + + * @param {Boolean} [pExecuteOnlyIfConditionExists=true] If true, the deletion is only done if there is a condition.<br/> + * <strong>IMPORTANT: If this is set to false and there is no condition, every row in the table will be deleted!</strong> + * @param {String} [pTableName] The table for deleting data. If undefined, the from part of the SqlBuilder will be used. * @param {Number} [pTimeout=-1] * @return {Number} the number of rows affected * @throws {Error} if no table is provided @@ -1136,9 +1415,12 @@ SqlBuilder.prototype.deleteData = function(pExecuteOnlyIfConditionExists, pTable } /** - * Executes the SQL using db.cell and returns the result. + * Executes the SQL using db.cell and returns the result.<br/> + * Note: the default for pExecuteOnlyIfConditionExists is false becausse it is more natural to select all rows if no condition exists. * - * @param {Boolean} [pExecuteOnlyIfConditionExists=false] if true and there is no condition, "" is returned + * @param {Boolean} [pExecuteOnlyIfConditionExists=false] if true and there is no condition, "" or the provided FallbackValue is returned + * @param {AnyValue} [pFallbackValue=""] here you can provide a fallback value if pExecuteOnlyIfConditionExists is true and the SqlBuilder has no condition.<br/> + * This is intended for e.g. select count(*) from ... because there a default value of "0" is more helpful * @return {String} the result of the query */ SqlBuilder.prototype.cell = function(pExecuteOnlyIfConditionExists, pFallbackValue) @@ -1155,7 +1437,8 @@ SqlBuilder.prototype.cell = function(pExecuteOnlyIfConditionExists, pFallbackVal } /** - * Executes the SQL using db.array(db.ROW, ...) and returns the result. + * Executes the SQL using db.array(db.ROW, ...) and returns the result.<br/> + * Note: the default for pExecuteOnlyIfConditionExists is false becausse it is more natural to select all rows if no condition exists. * * @param {Boolean} [pExecuteOnlyIfConditionExists=false] if true and there is no condition, [] is returned * @param {Number} [pMaxRows=0] @@ -1168,7 +1451,8 @@ SqlBuilder.prototype.arrayRow = function (pExecuteOnlyIfConditionExists, pMaxRow } /** - * Executes the SQL using db.array(db.COLUMN, ...) and returns the result. + * Executes the SQL using db.array(db.COLUMN, ...) and returns the result.<br/> + * Note: the default for pExecuteOnlyIfConditionExists is false becausse it is more natural to select all rows if no condition exists. * * @param {Boolean} [pExecuteOnlyIfConditionExists=false] if true and there is no condition, [] is returned * @param {Number} [pMaxRows=0] @@ -1181,7 +1465,8 @@ SqlBuilder.prototype.arrayColumn = function (pExecuteOnlyIfConditionExists, pMax } /** - * Executes the SQL using db.array and returns the result. + * Executes the SQL using db.array and returns the result.<br/> + * Note: the default for pExecuteOnlyIfConditionExists is false becausse it is more natural to select all rows if no condition exists. * * @param {Number} pType db.ROW or db.COLUMN * @param {Boolean} [pExecuteOnlyIfConditionExists=false] if true and there is no condition, [] is returned @@ -1205,7 +1490,8 @@ SqlBuilder.prototype.array = function(pType, pExecuteOnlyIfConditionExists, pMax } /** - * Executes the SQL using db.arrayPage and returns the result. + * Executes the SQL using db.arrayPage and returns the result.<br/> + * Note: the default for pExecuteOnlyIfConditionExists is false becausse it is more natural to select all rows if no condition exists. * * @param {Number} pType db.ROW or db.COLUMN * @param {Number} pStartIndex @@ -1231,7 +1517,8 @@ SqlBuilder.prototype.arrayPage = function(pType, pStartIndex, pRowCount, pExecut } /** - * Executes the SQL using db.table and returns the result. + * Executes the SQL using db.table and returns the result.<br/> + * Note: the default for pExecuteOnlyIfConditionExists is false becausse it is more natural to select all rows if no condition exists. * * @param {Boolean} [pExecuteOnlyIfConditionExists=false] if true and there is no condition, [] is returned * @param {Number} [pMaxRows=0] @@ -1254,7 +1541,8 @@ SqlBuilder.prototype.table = function(pExecuteOnlyIfConditionExists, pMaxRows, p } /** - * Executes the SQL using db.tablePage and returns the result. + * Executes the SQL using db.tablePage and returns the result.<br/> + * Note: the default for pExecuteOnlyIfConditionExists is false becausse it is more natural to select all rows if no condition exists. * * @param {Number} pStartIndex * @param {Number} pRowCount @@ -1279,6 +1567,8 @@ SqlBuilder.prototype.tablePage = function(pStartIndex, pRowCount, pExecuteOnlyIf } /** + * checks if an update /delete statement should be called or not + * @return {Boolean} * @private */ SqlBuilder.prototype._checkForUpdate = function(pExecuteOnlyIfConditionExists) @@ -1290,6 +1580,8 @@ SqlBuilder.prototype._checkForUpdate = function(pExecuteOnlyIfConditionExists) } /** + * checks if a select statement should be called or not + * @return {Boolean} * @private */ SqlBuilder.prototype._checkForSelect = function(pExecuteOnlyIfConditionExists) @@ -2266,8 +2558,9 @@ SqlUtils.getResolvingCaseWhen = function(pKeyValueArray, pDbFieldName, pLocale) /** * Will quote all prepared statement values from the given statement. - * @param {[String, String[]]} pStatement Same as first paraemter of db.translateStatement. - * @param {([String, String[]]) => String} pExecutionCallback A function which must return the final SQL. + * + * @param {PreparedSqlArray} pStatement Same as first paraemter of db.translateStatement. + * @param {Callback} pExecutionCallback (PreparedSqlArray) => String A function which must return the final SQL. * @return The SQL, same as the result of db.translateStatement. */ SqlUtils.translateWithQuotes = function(pStatement, pExecutionCallback) @@ -2296,7 +2589,9 @@ SqlUtils.translateWithQuotes = function(pStatement, pExecutionCallback) /** * Will quote all prepared statement values from the given statement. - * @param {[String, String[]]} pStatement Same as the first parameter of db.translateStatement. + * + * @param {PreparedSqlArray} pStatement Same as the first parameter of db.translateStatement. + * @param {String} [pAlias] the alias which should be used for db.translateStatement() * @returns {String} The SQL, same as the result of db.translateStatement. */ SqlUtils.translateStatementWithQuotes = function(pStatement, pAlias) @@ -2312,7 +2607,9 @@ SqlUtils.translateStatementWithQuotes = function(pStatement, pAlias) /** * Will quote all prepared statement values from the given statement. - * @param {[String, String[]]} pStatement Same as the first parameter of db.translateCondition. + * + * @param {PreparedSqlArray} pStatement Same as the first parameter of db.translateCondition. + * @param {String} [pAlias] the alias which should be used for db.translateStatement() * @returns {String} The SQL, same as the result of db.translateCondition. */ SqlUtils.translateConditionWithQuotes = function(pStatement, pAlias) @@ -2354,9 +2651,9 @@ SqlUtils.parseField = function(pField) return [alias, pField] } -SqlUtils.replaceConditionTemplate = function(pCond, pPlaceholder, pReplacement) +SqlUtils.replaceConditionTemplate = function(pCondition, pPlaceholder, pReplacement) { - //SqlUtils.replaceConditionTemplate(pCond, '#', SqlUtils.parseField(pFieldOrCond).join(".")) + //SqlUtils.replaceConditionTemplate(pCondition, '#', SqlUtils.parseField(pFieldOrCond).join(".")) //this function looks more complex (and slower) than it actually is /* the following regex looks like this after javascript-escaping of the backslash: (?<!\\)((?:\\\\)*)# @@ -2382,5 +2679,5 @@ SqlUtils.replaceConditionTemplate = function(pCond, pPlaceholder, pReplacement) //now that we've replaced the correct field placeholder let's replace the escaped placeholder sign "\#" to a normal placeholder sign "#" replacements["\\\\" + pPlaceholder] = pPlaceholder - return text.replaceAll(pCond, replacements); + return text.replaceAll(pCondition, replacements); } \ No newline at end of file