@mlagie/sql-connector 1.0.0

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.
@@ -0,0 +1,159 @@
1
+ # Documentation du module `sql-connector`
2
+
3
+ Le module `sql-connector` permet de gérer les connexions à une base de données MySQL, de définir des schémas de tables, et d'interagir avec les données de manière simple et efficace.
4
+
5
+ ## Importation du module
6
+
7
+ ```javascript
8
+ const { Schema, connect, logout, Model, client, sqlType } = require('sql-connector');
9
+ ```
10
+
11
+ ### Fonctions
12
+
13
+ `connect(config)` Établit une connexion à la base de données.
14
+
15
+ * Paramètres:
16
+ * `config` (Object) : La configuration de la connexion à la base de données.
17
+ * `host` (string) : L'hôte de la base de données.
18
+ * `port` (number) : Le port de la base de données.
19
+ * `user` (string) : Le nom d'utilisateur pour la connexion.
20
+ * `password` (string) : Le mot de passe pour la connexion.
21
+ * `database` (string) : Le nom de la base de données.
22
+ * `ect` pour en savoir plus vous pouvez vous rendre sur https://github.com/mysqljs/mysql dans la section `Connection options`
23
+
24
+ * ### Exemple:
25
+
26
+ ```javascript
27
+ const config = {
28
+ host: 'localhost',
29
+ port: 3306,
30
+ user: 'root',
31
+ password: 'password',
32
+ database: 'mydatabase'
33
+ };
34
+ await connect(config);
35
+ ```
36
+
37
+ `logout()` Ferme la connexion à la base de données.
38
+
39
+ * ### Exemple:
40
+
41
+ ```javascript
42
+ await logout();
43
+ ```
44
+
45
+ ### Classes `Schema`
46
+
47
+ Représente un schéma de base de données.
48
+ * Constructeur:
49
+ * Schema(schemaDict) : Crée une instance de Schema.
50
+ * schemaDict (Object) : Un dictionnaire définissant le schéma.
51
+
52
+ * Exemple
53
+
54
+ ```javascript
55
+ const transferSchema = new Schema({
56
+ token: {
57
+ type: String,
58
+ length: 50
59
+ },
60
+ mdp: {
61
+ type: String,
62
+ length: 15
63
+ }
64
+ });
65
+ ```
66
+ ## Class Model
67
+ Représente un modèle de base de données.
68
+ * ### Constructeur :
69
+ * `Model(name, schema)` : Crée une instance de `Model`.
70
+ * `name (string)` : Le nom de la table de base de données.
71
+ * `schema (Schema)` : Le schéma de la table de base de données.
72
+ * ### Méthodes :
73
+ * `generateCreateTableStatement(schema)` : Génère une requête SQL pour créer une table.
74
+ * `save(data)` : Sauvegarde des données dans la table.
75
+ * `findOne(filter, fields)` : Trouve une entrée unique dans la table.
76
+ * `find(filter, fields)` : Trouve des entrées dans la table.
77
+ * `customRequest(custom)` : Exécute une requête SQL personnalisée.
78
+ * `delete(filter)` : Supprime une entrée de la table.
79
+ * `dropTable()` : Supprime la table si elle existe.
80
+ * `generate_uuid()` : Génère un UUID unique pour le modèle.
81
+ * `createAllTables()` : **Crée toutes les tables dans le bon ordre selon les dépendances de clés étrangères.** (statique)
82
+ * ### Exemple
83
+ ```javascript
84
+ const userModel = new Model('users', transferSchema);
85
+ // Après avoir instancié tous les modèles :
86
+ await Model.createAllTables(); // Crée toutes les tables dans le bon ordre
87
+
88
+ // Sauvegarder des données
89
+ await userModel.save({ token: 'abc123', mdp: 'password' });
90
+
91
+ // Trouver une entrée
92
+ const user = await userModel.findOne({ token: 'abc123' });
93
+
94
+ // Supprimer une entrée
95
+ await userModel.delete({ token: 'abc123' });
96
+ ```
97
+ ## Class ModelInstance
98
+ Représente une instance d'un modèle de base de données.
99
+ * ### Constructeur:
100
+ * `ModelInstance(name, data)` : Crée une instance de `ModelInstance`.
101
+ * `name (string)` : Le nom de la table de base de données.
102
+ * `data (Object)` : Les données de l'instance.
103
+ * ### Méthodes :
104
+ * `updateOne(model)` : Met à jour une entrée unique dans la table.
105
+ * `delete(model)` : Supprime une entrée unique dans la table.
106
+ * `customRequest(custom)` : Exécute une requête SQL personnalisée.
107
+ * ### Exemple
108
+ ```javascript
109
+ const userInstance = new ModelInstance('users', { token: 'abc123', mdp: 'password' });
110
+
111
+ // Mettre à jour des données
112
+ await userInstance.updateOne({ mdp: 'newpassword' });
113
+
114
+ // Supprimer des données
115
+ await userInstance.delete({ token: 'abc123' });
116
+ ```
117
+ # Types SQL
118
+ Le module fournit également une map des types SQL courants via `sqlType`.
119
+ ## Type
120
+ * String
121
+ * Number
122
+ * Boolean
123
+ * Object
124
+ * Array
125
+ * Now
126
+ * Float
127
+ * Text
128
+ * DateTime
129
+ * Timestamp
130
+ * ### Exemple
131
+ ```javascript
132
+ console.log(sqlType.String); // "String"
133
+ console.log(sqlTypeMap.String); // "VARCHAR"
134
+ ```
135
+ ## Conclusion
136
+ Le module `sql-connector` fournit une interface simple et efficace pour interagir avec une base de données MySQL, permettant de définir des schémas, de gérer des connexions, et de manipuler des données de manière intuitive.
137
+
138
+ # Client
139
+ Le module client est un objet utilisé pour stocker des fonctions. Il sert de conteneur centralisé pour diverses fonctions qui peuvent être utilisées dans différentes parties de l'application.
140
+
141
+ ### Utilisation
142
+ Pour ajouter une fonction à l'objet client, vous pouvez simplement définir une nouvelle propriété sur l'objet et lui assigner une fonction.
143
+ * ### Exemple
144
+ ```javascript
145
+ module.exports = client => {
146
+ client.checkServer() {
147
+ if (server.islaunch())
148
+ return 1;
149
+ return 0;
150
+ };
151
+ };
152
+ ```
153
+ ### Avantages
154
+ * `Centralisation` : Toutes les fonctions liées à des opérations spécifiques peuvent être centralisées dans un seul objet, ce qui facilite la gestion et l'organisation du code.
155
+ * `Réutilisabilité` : Les fonctions stockées dans l'objet `client` peuvent être facilement réutilisées dans différentes parties de l'application.
156
+ * `Modularité` : En utilisant un objet pour stocker des fonctions, il est plus facile de maintenir et de mettre à jour le code, car les fonctions peuvent être ajoutées, modifiées ou supprimées sans affecter d'autres parties de l'application.
157
+
158
+ ## Conclusion
159
+ L'objet `client` est un outil puissant pour organiser et centraliser les fonctions dans votre application. En stockant des fonctions dans cet objet, vous pouvez améliorer la modularité, la réutilisabilité et la maintenabilité de votre code.
package/index.d.ts ADDED
@@ -0,0 +1,249 @@
1
+ import { PoolOptions } from "mysql2";
2
+
3
+ export type SqlType =
4
+ | "String"
5
+ | "Number"
6
+ | "Boolean"
7
+ | "Date"
8
+ | "Object"
9
+ | "Array"
10
+ | "Now"
11
+ | "Float"
12
+ | "Text"
13
+ | "DateTime"
14
+ | "Timestamp";
15
+
16
+ export interface SchemaField {
17
+ type: SqlType | { name: SqlType };
18
+ length?: number;
19
+ required?: boolean;
20
+ default?: any;
21
+ unique?: boolean;
22
+ auto_increment?: boolean;
23
+ foreignKey?: string;
24
+ customize?: string;
25
+ }
26
+
27
+ export interface SchemaDict {
28
+ [key: string]: SchemaField;
29
+ }
30
+
31
+ /**
32
+ * Represents a database schema.
33
+ *
34
+ * @example
35
+ * const transferSchema = new Schema({
36
+ * token: {
37
+ * type: String,
38
+ * length: 50
39
+ * },
40
+ * mdp: {
41
+ * type: String,
42
+ * length: 15
43
+ * }
44
+ * });
45
+ */
46
+ export class Schema {
47
+ constructor(schemaDict: SchemaDict);
48
+ schemaDict: SchemaDict;
49
+ }
50
+
51
+ /**
52
+ * Establishes a connection to the database using a given configuration.
53
+ * @param {Object} config Database connection configuration.
54
+ * @param {string} config.host The database host.
55
+ * @param {number} config.port The database port.
56
+ * @param {string} config.user The username for the connection.
57
+ * @param {string} config.password The password for the connection.
58
+ * @param {string} config.database The name of the database.
59
+ * @returns {Promise<void>} A promise that resolves when the connection is established.
60
+ *
61
+ * @example
62
+ * const config = {
63
+ * host: 'localhost',
64
+ * port: 6666,
65
+ * user: 'root',
66
+ * password: 'password',
67
+ * database: 'mydatabase'
68
+ * };
69
+ * await connect(config);
70
+ */
71
+ export function connect(config: PoolOptions): Promise<void>;
72
+
73
+ /**
74
+ * Closes the database connection.
75
+ * This function terminates the active database connection and records a logging message
76
+ * indicating whether the shutdown succeeded or failed.
77
+ *
78
+ * @returns {Promise<void>} A promise that resolves when the connection is closed.
79
+ *
80
+ * @example
81
+ * await logout();
82
+ */
83
+ export function logout(): Promise<void>;
84
+
85
+ /**
86
+ * Represents a database model.
87
+ * @class
88
+ */
89
+ export class Model {
90
+ static sqlTypeMap: Record<SqlType, string>;
91
+ static pendingModels: Model[];
92
+ name: string;
93
+ schema: Schema;
94
+ constructor(name: string, schema: Schema);
95
+ /**
96
+ * Crée toutes les tables dans l'ordre correct en fonction des foreign keys.
97
+ * @returns {Promise<void>}
98
+ */
99
+ static createAllTables(): Promise<void>;
100
+ /**
101
+ * Saves data to the database table.
102
+ * @param {Object} data The data to insert into the table.
103
+ * @returns {Promise<Object>} A promise that resolves with the result of the insertion.
104
+ * @throws {Error} Throws an error if the insert fails.
105
+ */
106
+ save(data: Record<string, any>): Promise<any>;
107
+ /**
108
+ * Récupère plusieurs entrées de la table.
109
+ * @param {Object} [options] - Options de requête (attributs, where, order, limit).
110
+ * @param {string[]} [options.attributes] - Champs à retourner.
111
+ * @param {Object} [options.where] - Filtres (clé/valeur).
112
+ * @param {Array} [options.order] - Ex: [['points', 'DESC']]
113
+ * @param {number} [options.limit] - Limite de résultats.
114
+ * @returns {Promise<Array<Object>>}
115
+ */
116
+ findAll(options?: {
117
+ attributes?: string[];
118
+ where?: Record<string, any>;
119
+ order?: [string, string][];
120
+ limit?: number;
121
+ }): Promise<any[]>;
122
+ /**
123
+ * Finds a unique entry in the database table based on the filter provided.
124
+ * @param {Object} filter An object containing the key-value pairs to use to generate the search condition.
125
+ * @param {string[]} [fields=["*"]] An array of field names to return in the result.
126
+ * @returns {Promise<ModelInstance|number>} A promise that resolves to a ModelInstance if an entry is found, otherwise 0.
127
+ */
128
+ findOne(filter: Record<string, any>, fields?: string[]): Promise<ModelInstance | number>;
129
+ /**
130
+ * Finds a record in the database based on the provided filter.
131
+ *
132
+ * @async
133
+ * @param {Object} filter - The filter criteria for the query. Should be an object where keys are column names and values are the values to filter by.
134
+ * @param {Array<string>} [fields=["*"]] - The fields to select in the query. Defaults to selecting all fields.
135
+ * @returns {Promise<ModelInstance|number>} - A promise that resolves to a `ModelInstance` if a record is found, or `0` if no records match the filter.
136
+ *
137
+ * @example
138
+ * // Example usage:
139
+ * const filter = { id: 1 };
140
+ * const fields = ["id", "name"];
141
+ * MyTable.find(filter, fields).then((result) => {
142
+ * if (result === 0) {
143
+ * console.log("No records found.");
144
+ * } else {
145
+ * console.log("Record found:", result);
146
+ * }
147
+ * }).catch((err) => {
148
+ * console.error("Error:", err);
149
+ * });
150
+ */
151
+ find(filter: Record<string, any>, fields?: string[]): Promise<ModelInstance | number>;
152
+ /**
153
+ *
154
+ * @param {Object} filter The filter criteria for the query. Should be an object where keys are column names and values are the values to filter by.
155
+ * @returns {Promise<ModelInstance|number>} - A promise that resolves to a `ModelInstance` if a record is found, or `0` if no records match the filter.
156
+ */
157
+ count(filter?: Record<string, any>): Promise<any>;
158
+ /**
159
+ * Runs a custom SQL_request query.
160
+ * @param {string} custom The custom SQL_request query to execute.
161
+ * @returns {Promise<void>} A promise that resolves when the query is executed.
162
+ * @throws {Error} Throws an error if query execution fails.
163
+ */
164
+ customRequest(custom: string): Promise<any>;
165
+ /**
166
+ * Supprime une entrée de la table SQL correspondant au filtre fourni.
167
+ *
168
+ * @async
169
+ * @function delete
170
+ * @param {Object} filter - Un objet représentant les conditions de filtre pour la suppression.
171
+ * @returns {Promise<number>} Une promesse qui se résout à 0 si aucune ligne n'a été supprimée,
172
+ * ou à une instance de ModelInstance représentant la ligne supprimée.
173
+ * @throws {Error} Lance une erreur si la requête SQL échoue.
174
+ */
175
+ delete(filter: Record<string, any>): Promise<number | ModelInstance>;
176
+ /**
177
+ * Asynchronously drops a table if it exists in the database.
178
+ *
179
+ * This function constructs a SQL_request query to drop a table with the name specified
180
+ * by the `this.name` property. It then executes the query using a promise-based
181
+ * approach. If the query is successful, the result is logged to the console.
182
+ * If an error occurs during the execution of the query, an error message is logged.
183
+ *
184
+ * @returns {Promise<void>} A promise that resolves when the query execution is complete.
185
+ */
186
+ dropTable(): Promise<void>;
187
+ /**
188
+ * Generates a unique UUID for the current model.
189
+ *
190
+ * This function generates a UUID using the SQL_request `UUID()` function and checks if the generated UUID
191
+ * already exists in the database for the current model. If the UUID is unique, it is returned.
192
+ * Otherwise, the function resolves to `null`.
193
+ *
194
+ * @returns {Promise<string|null>} A promise that resolves to a unique UUID string if successful, or `null` if an error occurs or the UUID is not unique.
195
+ *
196
+ * @example
197
+ * const uuid = await model.generate_uuid();
198
+ * if (uuid) {
199
+ * console.log(`Generated UUID: ${uuid}`);
200
+ * } else {
201
+ * console.log('Failed to generate a unique UUID.');
202
+ * }
203
+ *
204
+ * @throws {Error} If there is an error executing the SQL_request query.
205
+ */
206
+ generate_uuid(var_uuid?: string): Promise<string | null>;
207
+ }
208
+
209
+ /**
210
+ * Represents an instance of a database model.
211
+ * @class
212
+ */
213
+ export class ModelInstance {
214
+ name: string;
215
+ data: any;
216
+ schema?: Schema;
217
+ constructor(name: string, data: any, schema?: Schema);
218
+ /**
219
+ * Updates a single entry in the database table.
220
+ *
221
+ * @param {Object} model An object containing the key-value pairs to use for updating.
222
+ * @returns {int} A promise that resolves with updated data.
223
+ * @throws {Error} Throws an error if the update fails.
224
+ */
225
+ updateOne(model: Record<string, any>): Promise<number>;
226
+ /**
227
+ * Deletes a single entry in the database table.
228
+ * @param {Object} model An object containing the key-value pairs to use for deletion.
229
+ * @returns {Promise<Object>} A promise that resolves with the data deleted.
230
+ * @throws {Error} Throws an error if the deletion fails.
231
+ */
232
+ delete(filter: Record<string, any>): Promise<number | ModelInstance>;
233
+ /**
234
+ * Deletes a single entry in the database table based on the instance data.
235
+ * @returns {Promise<number>} A promise that resolves to the number of rows deleted.
236
+ * @throws {Error} Throws an error if the deletion fails.
237
+ */
238
+ deleteOne(): Promise<number>;
239
+ /**
240
+ * Runs a custom SQL_request query.
241
+ * @param {string} custom The custom SQL_request query to execute.
242
+ * @returns {Promise<void>} A promise that resolves when the query is executed.
243
+ * @throws {Error} Throws an error if query execution fails.
244
+ */
245
+ customRequest(custom: string): Promise<any>;
246
+ }
247
+
248
+ export const client: Record<string, any>;
249
+ export const sqlType: Record<string, SqlType>;