@xata.io/client 0.0.0-beta.f12621e → 0.0.0-beta.fef71a6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,43 +1,128 @@
1
1
  import { XataRecord, Repository } from '..';
2
- import { Constraint, DeepConstraint, FilterConstraints, SortDirection, SortFilter } from './filters';
3
- import { PaginationOptions, BasePage, PaginationQueryMeta, Page } from './pagination';
2
+ import { FilterExpression, SortExpression, PageConfig, ColumnsFilter } from '../api/schemas';
3
+ import { DeepConstraint, FilterConstraints, SortDirection, SortFilter } from './filters';
4
+ import { PaginationOptions, Page, Paginable, PaginationQueryMeta } from './pagination';
4
5
  import { Selectable, SelectableColumn, Select } from './selection';
5
- export declare type QueryOptions<T> = {
6
+ export declare type QueryOptions<T extends XataRecord> = {
6
7
  page?: PaginationOptions;
7
- columns?: Array<keyof Selectable<T>>;
8
+ columns?: Extract<keyof Selectable<T>, string>[];
8
9
  sort?: SortFilter<T> | SortFilter<T>[];
9
10
  };
10
- declare type QueryOrConstraint<T extends XataRecord, R extends XataRecord> = Query<T, R> | Constraint<T>;
11
- export declare class Query<T extends XataRecord, R extends XataRecord = T> implements BasePage<T, R> {
12
- table: string;
13
- repository: Repository<T>;
14
- readonly $any?: QueryOrConstraint<T, R>[];
15
- readonly $all?: QueryOrConstraint<T, R>[];
16
- readonly $not?: QueryOrConstraint<T, R>[];
17
- readonly $none?: QueryOrConstraint<T, R>[];
18
- readonly $sort?: Record<string, SortDirection>;
19
- readonly columns: SelectableColumn<T>[];
20
- readonly query: Query<T, R>;
11
+ export declare type QueryTableOptions = {
12
+ filter: FilterExpression;
13
+ sort?: SortExpression;
14
+ page?: PageConfig;
15
+ columns?: ColumnsFilter;
16
+ };
17
+ /**
18
+ * Query objects contain the information of all filters, sorting, etc. to be included in the database query.
19
+ *
20
+ * Query objects are immutable. Any method that adds more constraints or options to the query will return
21
+ * a new Query object containing the both the previous and the new constraints and options.
22
+ */
23
+ export declare class Query<T extends XataRecord, R extends XataRecord = T> implements Paginable<T, R> {
24
+ #private;
21
25
  readonly meta: PaginationQueryMeta;
22
26
  readonly records: R[];
23
- constructor(repository: Repository<T> | null, table: string, data: Partial<Query<T, R>>, parent?: Query<T, R>);
27
+ constructor(repository: Repository<T> | null, table: string, data: Partial<QueryTableOptions>, parent?: Partial<QueryTableOptions>);
28
+ getQueryOptions(): QueryTableOptions;
29
+ /**
30
+ * Builds a new query object representing a logical OR between the given subqueries.
31
+ * @param queries An array of subqueries.
32
+ * @returns A new Query object.
33
+ */
24
34
  any(...queries: Query<T, R>[]): Query<T, R>;
35
+ /**
36
+ * Builds a new query object representing a logical AND between the given subqueries.
37
+ * @param queries An array of subqueries.
38
+ * @returns A new Query object.
39
+ */
25
40
  all(...queries: Query<T, R>[]): Query<T, R>;
41
+ /**
42
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
43
+ * @param queries An array of subqueries.
44
+ * @returns A new Query object.
45
+ */
26
46
  not(...queries: Query<T, R>[]): Query<T, R>;
47
+ /**
48
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
49
+ * @param queries An array of subqueries.
50
+ * @returns A new Query object.
51
+ */
27
52
  none(...queries: Query<T, R>[]): Query<T, R>;
53
+ /**
54
+ * Builds a new query object adding one or more constraints. Examples:
55
+ *
56
+ * ```
57
+ * query.filter("columnName", columnValue)
58
+ * query.filter({
59
+ * "columnName": columnValue
60
+ * })
61
+ * query.filter({
62
+ * "columnName": operator(columnValue) // Use gt, gte, lt, lte, startsWith,...
63
+ * })
64
+ * ```
65
+ *
66
+ * @param constraints
67
+ * @returns A new Query object.
68
+ */
28
69
  filter(constraints: FilterConstraints<T>): Query<T, R>;
29
- filter<F extends keyof T>(column: F, value: FilterConstraints<T[F]> | DeepConstraint<T[F]>): Query<T, R>;
70
+ filter<F extends keyof Selectable<T>>(column: F, value: FilterConstraints<T[F]> | DeepConstraint<T[F]>): Query<T, R>;
71
+ /**
72
+ * Builds a new query with a new sort option.
73
+ * @param column The column name.
74
+ * @param direction The direction. Either ascending or descending.
75
+ * @returns A new Query object.
76
+ */
30
77
  sort<F extends keyof T>(column: F, direction: SortDirection): Query<T, R>;
31
- getPaginated<Options extends QueryOptions<T>>(options?: Options): Promise<Page<T, typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R>>;
78
+ /**
79
+ * Builds a new query specifying the set of columns to be returned in the query response.
80
+ * @param columns Array of column names to be returned by the query.
81
+ * @returns A new Query object.
82
+ */
83
+ select<K extends SelectableColumn<T>>(columns: K[]): Query<T, Select<T, K>>;
84
+ getPaginated<Options extends QueryOptions<T>>(options?: Options): Promise<Page<T, GetWithColumnOptions<T, R, typeof options>>>;
32
85
  [Symbol.asyncIterator](): AsyncIterableIterator<R>;
33
- getIterator(chunk: number, options?: Omit<QueryOptions<T>, 'page'>): AsyncGenerator<R[]>;
34
- getMany<Options extends QueryOptions<T>>(options?: Options): Promise<(typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R)[]>;
35
- getOne<Options extends Omit<QueryOptions<T>, 'page'>>(options?: Options): Promise<(typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R) | null>;
36
- deleteAll(): Promise<number>;
86
+ getIterator<Options extends QueryOptions<T>>(chunk: number, options?: Omit<Options, 'page'>): AsyncGenerator<GetWithColumnOptions<T, R, typeof options>[]>;
87
+ /**
88
+ * Performs the query in the database and returns a set of results.
89
+ * @param options Additional options to be used when performing the query.
90
+ * @returns An array of records from the database.
91
+ */
92
+ getMany<Options extends QueryOptions<T>>(options?: Options): Promise<GetWithColumnOptions<T, R, typeof options>[]>;
93
+ /**
94
+ * Performs the query in the database and returns all the results.
95
+ * Warning: If there are a large number of results, this method can have performance implications.
96
+ * @param options Additional options to be used when performing the query.
97
+ * @returns An array of records from the database.
98
+ */
99
+ getAll<Options extends QueryOptions<T>>(options?: Omit<Options, 'page'>): Promise<GetWithColumnOptions<T, R, typeof options>[]>;
100
+ /**
101
+ * Performs the query in the database and returns the first result.
102
+ * @param options Additional options to be used when performing the query.
103
+ * @returns The first record that matches the query, or null if no record matched the query.
104
+ */
105
+ getOne<Options extends Omit<QueryOptions<T>, 'page'>>(options?: Options): Promise<GetWithColumnOptions<T, R, typeof options> | null>;
106
+ /**async deleteAll(): Promise<number> {
107
+ // TODO: Return number of affected rows
108
+ return 0;
109
+ }**/
37
110
  nextPage(size?: number, offset?: number): Promise<Page<T, R>>;
38
111
  previousPage(size?: number, offset?: number): Promise<Page<T, R>>;
39
112
  firstPage(size?: number, offset?: number): Promise<Page<T, R>>;
40
113
  lastPage(size?: number, offset?: number): Promise<Page<T, R>>;
41
114
  hasNextPage(): boolean;
42
115
  }
116
+ /**
117
+ * Helper type to read options and compute the correct type for the result values
118
+ * T: Original type
119
+ * R: Default destination type
120
+ * Options: QueryOptions
121
+ *
122
+ * If the columns are overriden in the options, the result type is the pick of the original type and the columns
123
+ * If the columns are not overriden, the result type is the default destination type
124
+ */
125
+ declare type GetWithColumnOptions<T, R, Options> = Options extends {
126
+ columns: SelectableColumn<T>[];
127
+ } ? Select<T, Options['columns'][number]> : R;
43
128
  export {};
@@ -8,6 +8,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
12
+ if (kind === "m") throw new TypeError("Private method is not writable");
13
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
14
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
15
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
16
+ };
17
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
18
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
19
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
20
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
21
+ };
11
22
  var __asyncValues = (this && this.__asyncValues) || function (o) {
12
23
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
24
  var m = o[Symbol.asyncIterator], i;
@@ -27,32 +38,38 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar
27
38
  function reject(value) { resume("throw", value); }
28
39
  function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
29
40
  };
41
+ var _Query_table, _Query_repository, _Query_data;
30
42
  Object.defineProperty(exports, "__esModule", { value: true });
31
43
  exports.Query = void 0;
44
+ const lang_1 = require("../util/lang");
45
+ /**
46
+ * Query objects contain the information of all filters, sorting, etc. to be included in the database query.
47
+ *
48
+ * Query objects are immutable. Any method that adds more constraints or options to the query will return
49
+ * a new Query object containing the both the previous and the new constraints and options.
50
+ */
32
51
  class Query {
33
52
  constructor(repository, table, data, parent) {
34
- this.columns = ['*'];
35
- // Cursor pagination
36
- this.query = this;
53
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
54
+ _Query_table.set(this, void 0);
55
+ _Query_repository.set(this, void 0);
56
+ _Query_data.set(this, { filter: {} });
57
+ // Implements pagination
37
58
  this.meta = { page: { cursor: 'start', more: true } };
38
59
  this.records = [];
60
+ __classPrivateFieldSet(this, _Query_table, table, "f");
39
61
  if (repository) {
40
- this.repository = repository;
62
+ __classPrivateFieldSet(this, _Query_repository, repository, "f");
41
63
  }
42
64
  else {
43
- this.repository = this;
65
+ __classPrivateFieldSet(this, _Query_repository, this, "f");
44
66
  }
45
- this.table = table;
46
- // For some reason Object.assign(this, parent) didn't work in this case
47
- // so doing all this manually:
48
- this.$any = parent === null || parent === void 0 ? void 0 : parent.$any;
49
- this.$all = parent === null || parent === void 0 ? void 0 : parent.$all;
50
- this.$not = parent === null || parent === void 0 ? void 0 : parent.$not;
51
- this.$none = parent === null || parent === void 0 ? void 0 : parent.$none;
52
- this.$sort = parent === null || parent === void 0 ? void 0 : parent.$sort;
53
- Object.assign(this, data);
54
- // These bindings are used to support deconstructing
55
- // const { any, not, filter, sort } = xata.users.query()
67
+ __classPrivateFieldGet(this, _Query_data, "f").filter.$any = (_b = (_a = data.filter) === null || _a === void 0 ? void 0 : _a.$any) !== null && _b !== void 0 ? _b : (_c = parent === null || parent === void 0 ? void 0 : parent.filter) === null || _c === void 0 ? void 0 : _c.$any;
68
+ __classPrivateFieldGet(this, _Query_data, "f").filter.$all = (_e = (_d = data.filter) === null || _d === void 0 ? void 0 : _d.$all) !== null && _e !== void 0 ? _e : (_f = parent === null || parent === void 0 ? void 0 : parent.filter) === null || _f === void 0 ? void 0 : _f.$all;
69
+ __classPrivateFieldGet(this, _Query_data, "f").filter.$not = (_h = (_g = data.filter) === null || _g === void 0 ? void 0 : _g.$not) !== null && _h !== void 0 ? _h : (_j = parent === null || parent === void 0 ? void 0 : parent.filter) === null || _j === void 0 ? void 0 : _j.$not;
70
+ __classPrivateFieldGet(this, _Query_data, "f").filter.$none = (_l = (_k = data.filter) === null || _k === void 0 ? void 0 : _k.$none) !== null && _l !== void 0 ? _l : (_m = parent === null || parent === void 0 ? void 0 : parent.filter) === null || _m === void 0 ? void 0 : _m.$none;
71
+ __classPrivateFieldGet(this, _Query_data, "f").sort = (_o = data.sort) !== null && _o !== void 0 ? _o : parent === null || parent === void 0 ? void 0 : parent.sort;
72
+ __classPrivateFieldGet(this, _Query_data, "f").columns = (_q = (_p = data.columns) !== null && _p !== void 0 ? _p : parent === null || parent === void 0 ? void 0 : parent.columns) !== null && _q !== void 0 ? _q : ['*'];
56
73
  this.any = this.any.bind(this);
57
74
  this.all = this.all.bind(this);
58
75
  this.not = this.not.bind(this);
@@ -62,58 +79,80 @@ class Query {
62
79
  Object.defineProperty(this, 'table', { enumerable: false });
63
80
  Object.defineProperty(this, 'repository', { enumerable: false });
64
81
  }
65
- any(...queries) {
66
- return new Query(this.repository, this.table, {
67
- $any: (this.$any || []).concat(queries)
68
- }, this);
82
+ getQueryOptions() {
83
+ return __classPrivateFieldGet(this, _Query_data, "f");
69
84
  }
85
+ /**
86
+ * Builds a new query object representing a logical OR between the given subqueries.
87
+ * @param queries An array of subqueries.
88
+ * @returns A new Query object.
89
+ */
90
+ any(...queries) {
91
+ const $any = queries.map((query) => query.getQueryOptions().filter);
92
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $any } }, __classPrivateFieldGet(this, _Query_data, "f"));
93
+ }
94
+ /**
95
+ * Builds a new query object representing a logical AND between the given subqueries.
96
+ * @param queries An array of subqueries.
97
+ * @returns A new Query object.
98
+ */
70
99
  all(...queries) {
71
- return new Query(this.repository, this.table, {
72
- $all: (this.$all || []).concat(queries)
73
- }, this);
74
- }
100
+ const $all = queries.map((query) => query.getQueryOptions().filter);
101
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $all } }, __classPrivateFieldGet(this, _Query_data, "f"));
102
+ }
103
+ /**
104
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
105
+ * @param queries An array of subqueries.
106
+ * @returns A new Query object.
107
+ */
75
108
  not(...queries) {
76
- return new Query(this.repository, this.table, {
77
- $not: (this.$not || []).concat(queries)
78
- }, this);
79
- }
109
+ const $not = queries.map((query) => query.getQueryOptions().filter);
110
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $not } }, __classPrivateFieldGet(this, _Query_data, "f"));
111
+ }
112
+ /**
113
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
114
+ * @param queries An array of subqueries.
115
+ * @returns A new Query object.
116
+ */
80
117
  none(...queries) {
81
- return new Query(this.repository, this.table, {
82
- $none: (this.$none || []).concat(queries)
83
- }, this);
118
+ const $none = queries.map((query) => query.getQueryOptions().filter);
119
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $none } }, __classPrivateFieldGet(this, _Query_data, "f"));
84
120
  }
85
121
  filter(a, b) {
86
122
  if (arguments.length === 1) {
87
- const constraints = a;
88
- const queries = [];
89
- for (const [column, constraint] of Object.entries(constraints)) {
90
- queries.push({ [column]: constraint });
91
- }
92
- return new Query(this.repository, this.table, {
93
- $all: (this.$all || []).concat(queries)
94
- }, this);
123
+ const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
124
+ const $all = (0, lang_1.compact)([__classPrivateFieldGet(this, _Query_data, "f").filter.$all].flat().concat(constraints));
125
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $all } }, __classPrivateFieldGet(this, _Query_data, "f"));
95
126
  }
96
127
  else {
97
128
  const column = a;
98
129
  const value = b;
99
- return new Query(this.repository, this.table, {
100
- $all: (this.$all || []).concat({ [column]: value })
101
- }, this);
130
+ const $all = (0, lang_1.compact)([__classPrivateFieldGet(this, _Query_data, "f").filter.$all].flat().concat({ [column]: value }));
131
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $all } }, __classPrivateFieldGet(this, _Query_data, "f"));
102
132
  }
103
133
  }
134
+ /**
135
+ * Builds a new query with a new sort option.
136
+ * @param column The column name.
137
+ * @param direction The direction. Either ascending or descending.
138
+ * @returns A new Query object.
139
+ */
104
140
  sort(column, direction) {
105
- const sort = Object.assign(Object.assign({}, this.$sort), { [column]: direction });
106
- const q = new Query(this.repository, this.table, {
107
- $sort: sort
108
- }, this);
109
- return q;
141
+ const sort = Object.assign(Object.assign({}, __classPrivateFieldGet(this, _Query_data, "f").sort), { [column]: direction });
142
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { sort }, __classPrivateFieldGet(this, _Query_data, "f"));
143
+ }
144
+ /**
145
+ * Builds a new query specifying the set of columns to be returned in the query response.
146
+ * @param columns Array of column names to be returned by the query.
147
+ * @returns A new Query object.
148
+ */
149
+ select(columns) {
150
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { columns }, __classPrivateFieldGet(this, _Query_data, "f"));
110
151
  }
111
152
  getPaginated(options = {}) {
112
- return __awaiter(this, void 0, void 0, function* () {
113
- return this.repository._runQuery(this, options);
114
- });
153
+ return __classPrivateFieldGet(this, _Query_repository, "f").query(this, options);
115
154
  }
116
- [Symbol.asyncIterator]() {
155
+ [(_Query_table = new WeakMap(), _Query_repository = new WeakMap(), _Query_data = new WeakMap(), Symbol.asyncIterator)]() {
117
156
  return __asyncGenerator(this, arguments, function* _a() {
118
157
  var e_1, _b;
119
158
  try {
@@ -143,43 +182,69 @@ class Query {
143
182
  }
144
183
  });
145
184
  }
185
+ /**
186
+ * Performs the query in the database and returns a set of results.
187
+ * @param options Additional options to be used when performing the query.
188
+ * @returns An array of records from the database.
189
+ */
146
190
  getMany(options = {}) {
147
191
  return __awaiter(this, void 0, void 0, function* () {
148
192
  const { records } = yield this.getPaginated(options);
149
193
  return records;
150
194
  });
151
195
  }
152
- getOne(options = {}) {
196
+ /**
197
+ * Performs the query in the database and returns all the results.
198
+ * Warning: If there are a large number of results, this method can have performance implications.
199
+ * @param options Additional options to be used when performing the query.
200
+ * @returns An array of records from the database.
201
+ */
202
+ getAll(options = {}) {
203
+ var e_2, _a;
153
204
  return __awaiter(this, void 0, void 0, function* () {
154
- const records = yield this.getMany(Object.assign(Object.assign({}, options), { page: { size: 1 } }));
155
- return records[0] || null;
205
+ const results = [];
206
+ try {
207
+ for (var _b = __asyncValues(this.getIterator(100, options)), _c; _c = yield _b.next(), !_c.done;) {
208
+ const page = _c.value;
209
+ results.push(...page);
210
+ }
211
+ }
212
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
213
+ finally {
214
+ try {
215
+ if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);
216
+ }
217
+ finally { if (e_2) throw e_2.error; }
218
+ }
219
+ return results;
156
220
  });
157
221
  }
158
- deleteAll() {
222
+ /**
223
+ * Performs the query in the database and returns the first result.
224
+ * @param options Additional options to be used when performing the query.
225
+ * @returns The first record that matches the query, or null if no record matched the query.
226
+ */
227
+ getOne(options = {}) {
159
228
  return __awaiter(this, void 0, void 0, function* () {
160
- // TODO: Return number of affected rows
161
- return 0;
229
+ const records = yield this.getMany(Object.assign(Object.assign({}, options), { page: { size: 1 } }));
230
+ return records[0] || null;
162
231
  });
163
232
  }
233
+ /**async deleteAll(): Promise<number> {
234
+ // TODO: Return number of affected rows
235
+ return 0;
236
+ }**/
164
237
  nextPage(size, offset) {
165
- return __awaiter(this, void 0, void 0, function* () {
166
- return this.firstPage(size, offset);
167
- });
238
+ return this.firstPage(size, offset);
168
239
  }
169
240
  previousPage(size, offset) {
170
- return __awaiter(this, void 0, void 0, function* () {
171
- return this.firstPage(size, offset);
172
- });
241
+ return this.firstPage(size, offset);
173
242
  }
174
243
  firstPage(size, offset) {
175
- return __awaiter(this, void 0, void 0, function* () {
176
- return this.getPaginated({ page: { size, offset } });
177
- });
244
+ return this.getPaginated({ page: { size, offset } });
178
245
  }
179
246
  lastPage(size, offset) {
180
- return __awaiter(this, void 0, void 0, function* () {
181
- return this.getPaginated({ page: { size, offset, before: 'end' } });
182
- });
247
+ return this.getPaginated({ page: { size, offset, before: 'end' } });
183
248
  }
184
249
  hasNextPage() {
185
250
  return this.meta.page.more;
@@ -0,0 +1,41 @@
1
+ import { Selectable } from './selection';
2
+ /**
3
+ * Represents an identifiable record from the database.
4
+ */
5
+ export interface Identifiable {
6
+ /**
7
+ * Unique id of this record.
8
+ */
9
+ id: string;
10
+ }
11
+ /**
12
+ * Represents a persisted record from the database.
13
+ */
14
+ export interface XataRecord extends Identifiable {
15
+ /**
16
+ * Metadata of this record.
17
+ */
18
+ xata: {
19
+ /**
20
+ * Number that is increased every time the record is updated.
21
+ */
22
+ version: number;
23
+ };
24
+ /**
25
+ * Retrieves a refreshed copy of the current record from the database.
26
+ */
27
+ read(): Promise<this>;
28
+ /**
29
+ * Performs a partial update of the current record. On success a new object is
30
+ * returned and the current object is not mutated.
31
+ * @param data The columns and their values that have to be updated.
32
+ * @returns A new record containing the latest values for all the columns of the current record.
33
+ */
34
+ update(data: Partial<Selectable<this>>): Promise<this>;
35
+ /**
36
+ * Performs a deletion of the current record in the database.
37
+ *
38
+ * @throws If the record was already deleted or if an error happened while performing the deletion.
39
+ */
40
+ delete(): Promise<void>;
41
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,109 @@
1
+ import { FetchImpl } from '../api/fetcher';
2
+ import { Page } from './pagination';
3
+ import { Query, QueryOptions } from './query';
4
+ import { XataRecord } from './record';
5
+ import { Selectable, SelectableColumn, Select } from './selection';
6
+ export declare type Links = Record<string, Array<string[]>>;
7
+ /**
8
+ * Common interface for performing operations on a table.
9
+ */
10
+ export declare abstract class Repository<T extends XataRecord> extends Query<T> {
11
+ /**
12
+ * Creates a record in the table.
13
+ * @param object Object containing the column names with their values to be stored in the table.
14
+ * @returns The full persisted record.
15
+ */
16
+ abstract create(object: Selectable<T>): Promise<T>;
17
+ /**
18
+ * Creates multiple records in the table.
19
+ * @param objects Array of objects with the column names and the values to be stored in the table.
20
+ * @returns Array of the persisted records.
21
+ */
22
+ abstract createMany(objects: Selectable<T>[]): Promise<T[]>;
23
+ /**
24
+ * Queries a single record from the table given its unique id.
25
+ * @param id The unique id.
26
+ * @returns The persisted record for the given id or null if the record could not be found.
27
+ */
28
+ abstract read(id: string): Promise<T | null>;
29
+ /**
30
+ * Insert a single record with a unique id.
31
+ * @param id The unique id.
32
+ * @param object Object containing the column names with their values to be stored in the table.
33
+ * @returns The full persisted record.
34
+ */
35
+ abstract insert(id: string, object: Selectable<T>): Promise<T>;
36
+ /**
37
+ * Partially update a single record given its unique id.
38
+ * @param id The unique id.
39
+ * @param object The column names and their values that have to be updatd.
40
+ * @returns The full persisted record.
41
+ */
42
+ abstract update(id: string, object: Partial<Selectable<T>>): Promise<T>;
43
+ /**
44
+ * Updates or inserts a single record. If a record exists with the given id,
45
+ * it will be update, otherwise a new record will be created.
46
+ * @param id A unique id.
47
+ * @param object The column names and the values to be persisted.
48
+ * @returns The full persisted record.
49
+ */
50
+ abstract updateOrInsert(id: string, object: Selectable<T>): Promise<T>;
51
+ /**
52
+ * Deletes a record given its unique id.
53
+ * @param id The unique id.
54
+ * @throws If the record could not be found or there was an error while performing the deletion.
55
+ */
56
+ abstract delete(id: string): void;
57
+ abstract query<R extends XataRecord, Options extends QueryOptions<T>>(query: Query<T, R>, options: Options): Promise<Page<T, typeof options extends {
58
+ columns: SelectableColumn<T>[];
59
+ } ? Select<T, typeof options['columns'][number]> : R>>;
60
+ }
61
+ export declare class RestRepository<T extends XataRecord> extends Repository<T> {
62
+ #private;
63
+ constructor(client: BaseClient<any>, table: string);
64
+ create(object: Selectable<T>): Promise<T>;
65
+ createMany(objects: T[]): Promise<T[]>;
66
+ read(recordId: string): Promise<T | null>;
67
+ update(recordId: string, object: Partial<Selectable<T>>): Promise<T>;
68
+ insert(recordId: string, object: Selectable<T>): Promise<T>;
69
+ updateOrInsert(recordId: string, object: Selectable<T>): Promise<T>;
70
+ delete(recordId: string): Promise<void>;
71
+ query<R extends XataRecord, Options extends QueryOptions<T>>(query: Query<T, R>, options?: Options): Promise<Page<T, typeof options extends {
72
+ columns: SelectableColumn<T>[];
73
+ } ? Select<T, typeof options['columns'][number]> : R>>;
74
+ }
75
+ interface RepositoryFactory {
76
+ createRepository<T extends XataRecord>(client: BaseClient<any>, table: string): Repository<T>;
77
+ }
78
+ export declare class RestRespositoryFactory implements RepositoryFactory {
79
+ createRepository<T extends XataRecord>(client: BaseClient<any>, table: string): Repository<T>;
80
+ }
81
+ declare type BranchStrategyValue = string | undefined | null;
82
+ declare type BranchStrategyBuilder = () => BranchStrategyValue | Promise<BranchStrategyValue>;
83
+ declare type BranchStrategy = BranchStrategyValue | BranchStrategyBuilder;
84
+ declare type BranchStrategyOption = NonNullable<BranchStrategy | BranchStrategy[]>;
85
+ export declare type XataClientOptions = {
86
+ /**
87
+ * Fetch implementation. This option is only required if the runtime does not include a fetch implementation
88
+ * available in the global scope. If you are running your code on Deno or Cloudflare workers for example,
89
+ * you won't need to provide a specific fetch implementation. But for most versions of Node.js you'll need
90
+ * to provide one. Such as cross-fetch, node-fetch or isomorphic-fetch.
91
+ */
92
+ fetch?: FetchImpl;
93
+ databaseURL?: string;
94
+ branch: BranchStrategyOption;
95
+ /**
96
+ * API key to be used. You can create one in your account settings at https://app.xata.io/settings.
97
+ */
98
+ apiKey: string;
99
+ repositoryFactory?: RepositoryFactory;
100
+ };
101
+ export declare class BaseClient<D extends Record<string, Repository<any>>> {
102
+ #private;
103
+ options: XataClientOptions;
104
+ db: D;
105
+ constructor(options: XataClientOptions, links?: Links);
106
+ initObject<T>(table: string, object: object): T;
107
+ getBranch(): Promise<string>;
108
+ }
109
+ export {};