11# sql-data-api-client-js
22SQL Data Api client for Javascript
33
4+ - [ Install] ( #install )
5+ - [ Set Base Url] ( #set-base-url )
6+ - [ Authenticate] ( #authenticate )
7+ - [ Query Data From Sql Database] ( #query-tables-or-views )
8+ - [ Save Data Into Sql Database] ( #saving-data )
9+ * [ Save Array Of Object (Upsert(Merge) / Append / BulkInsert) ] ( #save-array-of-objects )
10+ * [ Save With AutoId] ( #save-with-auto-id )
11+ * [ Update] ( #update )
12+ * [ Delete Array] ( #delete )
13+ * [ Delete From] ( #delete-from )
14+ - [ Sql Execute] ( #sql-execute )
15+ - [ License] ( #license )
16+
417## Install
518
619> npm install sql-data-api
@@ -16,11 +29,13 @@ setBaseUrl('https://api.worksheet.systems');
1629
1730```
1831
19- ## Authentication
32+ ## Authenticate
33+
34+ All sql-api operations should be authenticated unless public access allowed. Check Worksheet Systems Access Control model
2035
2136There are two types of authentication.
2237
23- 1 . you can set user name and password (use your Worksheet Systems account)
38+ 1 . you can set user name and password (use your Worksheet Systems account) (least preferable as you have to hardcode password)
2439
2540``` js
2641import { authenticate } from ' sql-data-api' ;
@@ -37,7 +52,7 @@ import { setUserAccessToken } from 'sql-data-api';
3752setUserAccessToken (' $ACCESS_TOKEN' )
3853```
3954
40- ## Query Data
55+ ## Query tables or views
4156
4257``` js
4358
@@ -57,9 +72,24 @@ export interface SqlReadQueryInfo {
5772}
5873
5974```
60- ### Query Usage
6175
62- #### A simple queries
76+ SQL Data api allows you to safely and securely query data from SQL tables/views. And you can use SQL functions, rename SQL columns, aggregate (groupBy) and even join tables
77+
78+ There are several ways you can define a query to the SQL Database. But, eventually it comes down to the few properties you have to specify:
79+
80+ - ** tableName** - name of SQL table or view. Also, you can specify alias e.g. ` myTable t ` , then you have to list your fields as ` t.Field1 ` etc
81+ - ** fields** - a list of fields to select. If ` fields ` property is not provided, then all table fields will be returned. Kind of ` select * from [tableName] ` . Also, there are several other scenarios:
82+ * rename fields e.g. ` Country CustomerCountry ` or ` cast(TransactionTime as Date) TransactionDate `
83+ * use SQL Functions e.g. ` concat(FirstName, ' ', LastName) FullName `
84+ * aggregate (group by): ` groupBy|Country, groupBy|City, sum(revenue) Revenue, count(*) Count `
85+ - ** filter** - defines a filter expression e.g. ` country = 'uk' and city = 'London' ` or you can use parameters and have filter as ` country = @country AND city = @city ` and provide parameters as an object` {country: 'UK', city: 'London'} ` . And you can use SQL functions as well: e.g.: ` cast(TransactionTime as Date) = '2021-11-21' `
86+ - ** orderBy** - define a columns to sort e.g.: `OrderDate DESC, OrderId ASC
87+ - ** top** ` - specify the number of records to return.
88+ - ** join** - combine rows from two or more tables, based on a related column between them. You can define array ` [JoinType, TableToJoin, JoinCondition] ` or: ` ['InnerJoin', 'Customers c', 'c.CustomerId = t.CustomerId'] `
89+
90+ ### Query Examples
91+
92+ ** A simple queries**
6393
6494``` js
6595import { sqlDataApi } from ' sql-data-api' ;
@@ -100,33 +130,164 @@ const itwms = await sqlDataApi('connectionName')
100130```
101131#### Aggregated query
102132
103- Add ` groupBy| ` prefix to the field and use aggregation functions e.g: sum, avg, count ...
133+ Add ` groupBy| ` prefix to the field you want to ` group by ` and use aggregation functions e.g: sum, avg, count ...
104134
105135``` js
106-
107136const aggData = await sqlDataApi (' connectionName' )
108137 .query (' someTableOrViewName' , {
109138 fields: ' groupBy|country, sum(revenue) revenue'
110139 });
111140
112141```
113142
114-
115- ## Save a array of items
143+ or with the same result
116144
117145``` js
118- save (tableName: string, items: ScalarObject[], itemsToDeleteOrSaveOptions?: Record< string, unknown> [] | SqlSaveOptions, saveOptions?: SqlSaveOptions): Promise < SqlSaveStatus> ;
146+ const aggData = await sqlDataApi (' connectionName' )
147+ .query (
148+ ' someTableOrViewName' ,
149+ ' groupBy|country, sum(revenue) revenue'
150+ );
151+ ```
152+
153+
154+ ## Saving Data
119155
156+ ### Save array of objects
157+
158+ Upsert(Merge), Append or BulkInsert an array of items into the table based on save options
159+ If third parameter is an array, it will delete records from the table. Only Key Fields must be provided
160+
161+ ``` js
162+ save (
163+ tableName: string,
164+ items: ScalarObject[],
165+ itemsToDeleteOrSaveOptions?: Record< string, unknown> [] | SqlSaveOptions,
166+ saveOptions?: SqlSaveOptions
167+ ): Promise < SqlSaveStatus> ;
168+
169+ /**
170+ * Sql Save operation config
171+ */
120172export interface SqlSaveOptions {
121- method : "Merge " | "Append " | "BulkInsert ";
122- batchSize ?: number ;
123- primaryKeys ?: string [];
124- batchProgressFunc ?: (processedCount : number , status : SqlSaveStatus ) => void ;
173+ /**
174+ * save types
175+ */
176+ method : "Merge " | "Append " | "BulkInsert ";
177+
178+ /**
179+ * a batch size for optimization point
180+ */
181+ batchSize ?: number ;
182+ /**
183+ * Define a primary key that should be used. Normally primary keys are taken from the table,
184+ * Use this property only if you want to upsert (merge) data on some other fields
185+ */
186+ primaryKeys ?: string [];
187+
188+ /**
189+ * Report progress on batch saving
190+ */
191+ batchProgressFunc ?: (processedCount : number , status : SqlSaveStatus ) => void ;
125192}
193+ ```
194+
195+ ** a simple save (upsert) example**
196+
197+ ``` js
198+ sqlDataApi (' someConnection' )
199+ .save (' someTable' , arrayOfItems)
200+ ```
201+
126202
127- saveWithAutoId (tableName : string, item : ScalarObject) : Promise < number > ;
203+ ### Save With Auto Id
128204
129- sqlExecute (sql: string, params?: ScalarObject): Promise < ScalarObject[] | unknown> ;
205+ Saves a single record into the database and returns autogenerated ID field value.
206+ SQL Table should have Auto Indentity on one of the fields
207+
208+ ``` js
209+ const person = {
210+ name: ' Adam'
211+ }
212+
213+ // table peopleTable should have Identity column
214+ person .id = await sqlDataApi (' someConnection' )
215+ .saveWithAutoId (' peopleTable' , person);
216+
217+ console .log (person)
218+ ```
219+
220+ ### Update
221+
222+ Updates data in the table based on filter parameter and returns number of rows affected
223+
224+ ``` js
225+ /**
226+ * Updates data in the table based on filter parameters
227+ * @returns Number of rows affected
228+ */
229+ async updateData (
230+ tableName: string,
231+ updateData: Record< string, ScalarType> ,
232+ filter?: string,
233+ filterParams?: Record< string, ScalarType>
234+ ): Promise < number>
235+ ```
236+
237+ ### Delete
238+
239+ Deletes rows from the table based on a primary keys. Only key fields have to be provided
240+
241+ ``` js
242+ /**
243+ * Deletes rows from the table. Only key fields have to be provided
244+ * @returns success
245+ */
246+ async delete (
247+ tableName: string,
248+ items: Record< string, ScalarType> []
249+ ): Promise < boolean>
250+ ```
251+
252+
253+ ### Delete From
254+
255+ Delete records from the table based on filter criteria
256+
257+ ``` js
258+ /**
259+ * Delete records from the table based on filter criteria
260+ */
261+ async deleteFrom (
262+ tableName: string,
263+ filter?: string,
264+ filterParams?: Record< string, ScalarType>
265+ ): Promise < number>
266+ ```
267+
268+ ## SQL Execute
269+
270+ Executes ` sql ` script in the server and returns either raw table or array of objects
271+
272+ ``` js
273+ /**
274+ * Executes a SQL Query or stored procedure with parameters
275+ * @returns Raw result (SqlQueryResponse) with a table in it
276+ */
277+ async sqlExecuteRaw (
278+ sql: string,
279+ params?: ScalarObject,
280+ paramDirections?: Record< string, string>
281+ ): Promise < SqlQueryResponse>
282+
283+ /**
284+ * Executes a SQL Query or stored procedure with parameters
285+ * @returns result as a list of arrays
286+ */
287+ async sqlExecute (
288+ sql: string,
289+ params?: ScalarObject
290+ ): Promise < ScalarObject[] | unknown>
130291
131292```
132293
0 commit comments