oktopios-orm 0.1.0__tar.gz → 0.3.0__tar.gz

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,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: oktopios-orm
3
- Version: 0.1.0
3
+ Version: 0.3.0
4
4
  Summary: ORM pour le langage Oktopios — modeles decores, migrations, query-builder (facon Doctrine / Django ORM)
5
5
  Author: Mouanwiya Ali Soule
6
6
  License: MIT License
@@ -31,7 +31,7 @@ Keywords: oktopios,orm,database,sqlite,migrations,okp
31
31
  Requires-Python: >=3.8
32
32
  Description-Content-Type: text/markdown
33
33
  License-File: LICENSE
34
- Requires-Dist: oktopios>=0.7.0
34
+ Requires-Dist: oktopios>=0.16.0
35
35
  Dynamic: license-file
36
36
 
37
37
  # oktopios-orm 🐙🗄️
@@ -100,13 +100,51 @@ Exécuter : `okp examples/blog.okp`
100
100
  - **`Query`** — constructeur de requêtes fluide : `select().where().orderBy().get()`,
101
101
  paramétré (anti-injection).
102
102
 
103
+ ## Relations `@ManyToOne` 🔗
104
+
105
+ ```okp
106
+ @Entity("auteurs")
107
+ class Auteur { @Id var id: int @Column("nom") var nom: string }
108
+
109
+ @Entity("articles")
110
+ class Article {
111
+ @Id var id: int
112
+ @Column("titre") var titre: string
113
+ @ManyToOne("Auteur") var auteur: any // colonne FK : auteur_id
114
+ }
115
+
116
+ var repoA = new Repo(db, new Auteur())
117
+ var a = new Auteur(); a.nom = "Awa"; repoA.save(a) // save réaffecte a.id
118
+
119
+ var repoArt = new Repo(db, new Article())
120
+ var art = new Article(); art.titre = "Hello"; art.auteur = a
121
+ repoArt.save(art) // écrit auteur_id = a.id
122
+
123
+ var trouve = repoArt.find(1)
124
+ print(trouve.auteur.nom) // -> "Awa" (objet lié chargé)
125
+ ```
126
+
127
+ `@ManyToOne("Classe")` crée une colonne de clé étrangère `<champ>_id` (ou le 2ᵉ
128
+ argument), écrite par `save` et chargée par `find`/`findBy` (un niveau).
129
+
130
+ ## Pagination 📄
131
+
132
+ ```okp
133
+ print(repoArt.count()) // nombre total de lignes
134
+ for (x in repoArt.page(10, 2)) { // page 2, 10 par page (entités hydratées)
135
+ print(x.titre)
136
+ }
137
+ // Bas niveau : Query.limit(n).offset(d) + Query.count()
138
+ ```
139
+
103
140
  ## Décorateurs reconnus
104
141
 
105
142
  | Décorateur | Cible | Effet |
106
143
  |---|---|---|
107
144
  | `@Entity("table")` | classe | nom de la table |
108
145
  | `@Column("colonne")` | champ | nom de la colonne |
109
- | `@Id` | champ | clé primaire |
146
+ | `@Id` | champ | clé primaire (auto-générée, réaffectée par `save`) |
147
+ | `@ManyToOne("Classe", "fk"?)` | champ | relation vers une autre entité |
110
148
 
111
149
  ## Licence
112
150
 
@@ -64,13 +64,51 @@ Exécuter : `okp examples/blog.okp`
64
64
  - **`Query`** — constructeur de requêtes fluide : `select().where().orderBy().get()`,
65
65
  paramétré (anti-injection).
66
66
 
67
+ ## Relations `@ManyToOne` 🔗
68
+
69
+ ```okp
70
+ @Entity("auteurs")
71
+ class Auteur { @Id var id: int @Column("nom") var nom: string }
72
+
73
+ @Entity("articles")
74
+ class Article {
75
+ @Id var id: int
76
+ @Column("titre") var titre: string
77
+ @ManyToOne("Auteur") var auteur: any // colonne FK : auteur_id
78
+ }
79
+
80
+ var repoA = new Repo(db, new Auteur())
81
+ var a = new Auteur(); a.nom = "Awa"; repoA.save(a) // save réaffecte a.id
82
+
83
+ var repoArt = new Repo(db, new Article())
84
+ var art = new Article(); art.titre = "Hello"; art.auteur = a
85
+ repoArt.save(art) // écrit auteur_id = a.id
86
+
87
+ var trouve = repoArt.find(1)
88
+ print(trouve.auteur.nom) // -> "Awa" (objet lié chargé)
89
+ ```
90
+
91
+ `@ManyToOne("Classe")` crée une colonne de clé étrangère `<champ>_id` (ou le 2ᵉ
92
+ argument), écrite par `save` et chargée par `find`/`findBy` (un niveau).
93
+
94
+ ## Pagination 📄
95
+
96
+ ```okp
97
+ print(repoArt.count()) // nombre total de lignes
98
+ for (x in repoArt.page(10, 2)) { // page 2, 10 par page (entités hydratées)
99
+ print(x.titre)
100
+ }
101
+ // Bas niveau : Query.limit(n).offset(d) + Query.count()
102
+ ```
103
+
67
104
  ## Décorateurs reconnus
68
105
 
69
106
  | Décorateur | Cible | Effet |
70
107
  |---|---|---|
71
108
  | `@Entity("table")` | classe | nom de la table |
72
109
  | `@Column("colonne")` | champ | nom de la colonne |
73
- | `@Id` | champ | clé primaire |
110
+ | `@Id` | champ | clé primaire (auto-générée, réaffectée par `save`) |
111
+ | `@ManyToOne("Classe", "fk"?)` | champ | relation vers une autre entité |
74
112
 
75
113
  ## Licence
76
114
 
@@ -1,2 +1,2 @@
1
1
  """oktopios-orm — ORM pour le langage Oktopios."""
2
- __version__ = "0.1.0"
2
+ __version__ = "0.3.0"
@@ -0,0 +1,308 @@
1
+ // =====================================================================
2
+ // oktopios-framework — Couche ORM
3
+ // Écrit EN Oktopios, s'appuie sur la réflexion et les décorateurs du
4
+ // langage (>= 0.6.0). Chargé via : use "framework/orm.okp"
5
+ //
6
+ // - Schema : migrations (génère le schéma SQL depuis les modèles décorés)
7
+ // - Repo : dépôt générique (save / all / findBy / remove + hydratation)
8
+ // - Query : constructeur de requêtes fluide
9
+ //
10
+ // Décorateurs reconnus :
11
+ // @Entity("table") (classe) -> nom de table
12
+ // @Column("colonne") (champ) -> nom de colonne
13
+ // @Id (champ) -> clé primaire
14
+ // =====================================================================
15
+ inject Type
16
+ inject DataImport
17
+
18
+ // ---------------------------------------------------------------------
19
+ // Schema — génération de schéma / migrations
20
+ // ---------------------------------------------------------------------
21
+ class Schema {
22
+ fun sqlType(t: string): string {
23
+ if (t == "int") { return "INTEGER" }
24
+ if (t == "float") { return "REAL" }
25
+ if (t == "bool") { return "INTEGER" }
26
+ return "TEXT"
27
+ }
28
+
29
+ fun tableName(entity: any): string {
30
+ var e = Type.annotation(entity, "Entity")
31
+ if (e != null) { return e[0] }
32
+ return Type.className(entity)
33
+ }
34
+
35
+ fun columnName(entity: any, champ: string): string {
36
+ var c = Type.fieldAnnotation(entity, champ, "Column")
37
+ if (c != null) { return c[0] }
38
+ return champ
39
+ }
40
+
41
+ fun idField(entity: any): string {
42
+ for (f in Type.fields(entity)) {
43
+ if (Type.fieldAnnotation(entity, f, "Id") != null) { return f }
44
+ }
45
+ return "id"
46
+ }
47
+
48
+ // --- Relations @ManyToOne("ClasseLiee", "colonne_fk"?) --------------
49
+ fun isRelation(entity: any, f: string): bool {
50
+ return Type.fieldAnnotation(entity, f, "ManyToOne") != null
51
+ }
52
+
53
+ fun relClass(entity: any, f: string): string {
54
+ var a = Type.fieldAnnotation(entity, f, "ManyToOne")
55
+ return a[0]
56
+ }
57
+
58
+ // Colonne de clé étrangère : 2e argument du décorateur, sinon <champ>_id.
59
+ fun fkColumn(entity: any, f: string): string {
60
+ var a = Type.fieldAnnotation(entity, f, "ManyToOne")
61
+ var n = 0
62
+ for (x in a) { n = n + 1 }
63
+ if (n > 1) { return a[1] }
64
+ return f + "_id"
65
+ }
66
+
67
+ fun createTableSQL(entity: any): string {
68
+ var defs = ""
69
+ for (f in Type.fields(entity)) {
70
+ if (defs != "") { defs = defs + ", " }
71
+ if (this.isRelation(entity, f) == true) {
72
+ // Relation -> colonne de clé étrangère entière.
73
+ defs = defs + this.fkColumn(entity, f) + " INTEGER"
74
+ } else {
75
+ var ligne = this.columnName(entity, f) + " " + this.sqlType(Type.fieldType(entity, f))
76
+ if (Type.fieldAnnotation(entity, f, "Id") != null) {
77
+ ligne = ligne + " PRIMARY KEY"
78
+ }
79
+ defs = defs + ligne
80
+ }
81
+ }
82
+ return "CREATE TABLE IF NOT EXISTS " + this.tableName(entity) + " (" + defs + ")"
83
+ }
84
+
85
+ // Crée la table dans la base à partir d'un exemple d'entité (modèle décoré)
86
+ fun migrate(db: string, entity: any): string {
87
+ var sql = this.createTableSQL(entity)
88
+ DataImport.execSQL(db, sql, [])
89
+ return sql
90
+ }
91
+ }
92
+
93
+ // ---------------------------------------------------------------------
94
+ // Repo — dépôt de données générique pour un modèle
95
+ // ---------------------------------------------------------------------
96
+ class Repo {
97
+ var db: string
98
+ var table: string
99
+ var model: string
100
+ var schema: Schema
101
+
102
+ // `sample` : une instance du modèle, utilisée pour lire les métadonnées
103
+ fun __construct(db: string, sample: any) {
104
+ this.db = db
105
+ this.schema = new Schema()
106
+ this.table = this.schema.tableName(sample)
107
+ this.model = Type.className(sample)
108
+ }
109
+
110
+ // Insère l'entité. La clé primaire (@Id) est omise pour laisser la base
111
+ // l'auto-générer ; `save` renvoie l'identifiant de la ligne créée.
112
+ // Pour une relation @ManyToOne, on écrit la clé étrangère (id de l'objet lié).
113
+ fun save(entity: any): int {
114
+ var idf = this.schema.idField(entity)
115
+ var colonnes = ""
116
+ var marques = ""
117
+ var valeurs = []
118
+ for (f in Type.fields(entity)) {
119
+ if (f != idf) {
120
+ if (colonnes != "") {
121
+ colonnes = colonnes + ", "
122
+ marques = marques + ", "
123
+ }
124
+ if (this.schema.isRelation(entity, f) == true) {
125
+ colonnes = colonnes + this.schema.fkColumn(entity, f)
126
+ marques = marques + "?"
127
+ var lie = Type.get(entity, f)
128
+ if (lie == null) {
129
+ valeurs = valeurs + [null]
130
+ } else {
131
+ valeurs = valeurs + [Type.get(lie, this.schema.idField(lie))]
132
+ }
133
+ } else {
134
+ colonnes = colonnes + this.schema.columnName(entity, f)
135
+ marques = marques + "?"
136
+ valeurs = valeurs + [Type.get(entity, f)]
137
+ }
138
+ }
139
+ }
140
+ var sql = "INSERT INTO " + this.table + " (" + colonnes + ") VALUES (" + marques + ")"
141
+ var nouvelId = DataImport.execSQL(this.db, sql, valeurs)
142
+ // Réaffecte la clé primaire générée sur l'entité (comme Django/Doctrine),
143
+ // pour que les relations ultérieures écrivent le bon id.
144
+ Type.set(entity, idf, nouvelId)
145
+ return nouvelId
146
+ }
147
+
148
+ // Transforme les lignes SQL (colonnes) en instances du modèle (champs).
149
+ // `avecRelations` : si vrai, charge aussi les objets liés (@ManyToOne),
150
+ // un seul niveau de profondeur (pas de récursion sur leurs relations).
151
+ fun hydrateOne(ligne: any, avecRelations: bool): any {
152
+ var obj = Type.create(this.model)
153
+ for (f in Type.fields(obj)) {
154
+ if (this.schema.isRelation(obj, f) == true) {
155
+ if (avecRelations == true) {
156
+ var fk = ligne[this.schema.fkColumn(obj, f)]
157
+ if (fk != null) {
158
+ var relRepo = new Repo(this.db, Type.create(this.schema.relClass(obj, f)))
159
+ var lies = relRepo.findByRaw(relRepo.idColumn(), fk, false)
160
+ var m = 0
161
+ for (z in lies) { m = m + 1 }
162
+ if (m > 0) { Type.set(obj, f, lies[0]) }
163
+ }
164
+ }
165
+ } else {
166
+ var col = this.schema.columnName(obj, f)
167
+ Type.set(obj, f, ligne[col])
168
+ }
169
+ }
170
+ return obj
171
+ }
172
+
173
+ fun hydrate(lignes: any): any {
174
+ var objets = []
175
+ for (ligne in lignes) {
176
+ objets = objets + [this.hydrateOne(ligne, true)]
177
+ }
178
+ return objets
179
+ }
180
+
181
+ fun idColumn(): string {
182
+ var ex = Type.create(this.model)
183
+ return this.schema.columnName(ex, this.schema.idField(ex))
184
+ }
185
+
186
+ // Hydrate une liste de lignes, en chargeant (ou non) les relations.
187
+ fun hydrateAll(lignes: any, avecRelations: bool): any {
188
+ var objets = []
189
+ for (ligne in lignes) {
190
+ objets = objets + [this.hydrateOne(ligne, avecRelations)]
191
+ }
192
+ return objets
193
+ }
194
+
195
+ fun all(): any {
196
+ return this.hydrate(DataImport.execSQL(this.db, "SELECT * FROM " + this.table, []))
197
+ }
198
+
199
+ fun findBy(colonne: string, valeur: any): any {
200
+ return this.findByRaw(colonne, valeur, true)
201
+ }
202
+
203
+ // Variante de findBy avec contrôle du chargement des relations
204
+ // (utilisée en interne pour éviter la récursion lors de l'hydratation).
205
+ fun findByRaw(colonne: string, valeur: any, avecRelations: bool): any {
206
+ var sql = "SELECT * FROM " + this.table + " WHERE " + colonne + " = ?"
207
+ return this.hydrateAll(DataImport.execSQL(this.db, sql, [valeur]), avecRelations)
208
+ }
209
+
210
+ // Récupère une entité par son id (relations chargées), ou null.
211
+ fun find(id: any): any {
212
+ var lies = this.findByRaw(this.idColumn(), id, true)
213
+ var n = 0
214
+ for (x in lies) { n = n + 1 }
215
+ if (n == 0) { return null }
216
+ return lies[0]
217
+ }
218
+
219
+ fun remove(colonne: string, valeur: any): int {
220
+ var sql = "DELETE FROM " + this.table + " WHERE " + colonne + " = ?"
221
+ return DataImport.execSQL(this.db, sql, [valeur])
222
+ }
223
+
224
+ // Nombre total de lignes de la table.
225
+ fun count(): int {
226
+ var lignes = DataImport.execSQL(this.db, "SELECT COUNT(*) AS n FROM " + this.table, [])
227
+ return lignes[0]["n"]
228
+ }
229
+
230
+ // Une page d'entités (relations chargées). `perPage` et `page` sont des
231
+ // entiers (page >= 1).
232
+ fun page(perPage: int, page: int): any {
233
+ var dec = (page - 1) * perPage
234
+ var sql = "SELECT * FROM " + this.table + " LIMIT " + perPage + " OFFSET " + dec
235
+ return this.hydrate(DataImport.execSQL(this.db, sql, []))
236
+ }
237
+ }
238
+
239
+ // ---------------------------------------------------------------------
240
+ // Query — constructeur de requêtes fluide
241
+ // ---------------------------------------------------------------------
242
+ class Query {
243
+ var db: string
244
+ var table: string
245
+ var champs: string
246
+ var conds: string
247
+ var params: any
248
+ var ordre: string
249
+ var borne: string
250
+
251
+ fun __construct(db: string, table: string) {
252
+ this.db = db
253
+ this.table = table
254
+ this.champs = "*"
255
+ this.conds = ""
256
+ this.params = []
257
+ this.ordre = ""
258
+ this.borne = ""
259
+ }
260
+
261
+ // Pagination : LIMIT n [OFFSET d]
262
+ fun limit(n: any): Query {
263
+ this.borne = " LIMIT " + n
264
+ return this
265
+ }
266
+ fun offset(d: any): Query {
267
+ this.borne = this.borne + " OFFSET " + d
268
+ return this
269
+ }
270
+
271
+ fun select(champs: string): Query {
272
+ this.champs = champs
273
+ return this
274
+ }
275
+
276
+ fun where(colonne: string, op: string, valeur: any): Query {
277
+ if (this.conds != "") { this.conds = this.conds + " AND " }
278
+ this.conds = this.conds + colonne + " " + op + " ?"
279
+ this.params = this.params + [valeur]
280
+ return this
281
+ }
282
+
283
+ fun orderBy(colonne: string, sens: string): Query {
284
+ this.ordre = " ORDER BY " + colonne + " " + sens
285
+ return this
286
+ }
287
+
288
+ fun sql(): string {
289
+ var s = "SELECT " + this.champs + " FROM " + this.table
290
+ if (this.conds != "") { s = s + " WHERE " + this.conds }
291
+ s = s + this.ordre
292
+ s = s + this.borne
293
+ return s
294
+ }
295
+
296
+ fun get(): any {
297
+ return DataImport.execSQL(this.db, this.sql(), this.params)
298
+ }
299
+
300
+ // Nombre total de lignes correspondant aux conditions (sans borne) —
301
+ // utile pour calculer le nombre de pages.
302
+ fun count(): int {
303
+ var s = "SELECT COUNT(*) AS n FROM " + this.table
304
+ if (this.conds != "") { s = s + " WHERE " + this.conds }
305
+ var lignes = DataImport.execSQL(this.db, s, this.params)
306
+ return lignes[0]["n"]
307
+ }
308
+ }
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: oktopios-orm
3
- Version: 0.1.0
3
+ Version: 0.3.0
4
4
  Summary: ORM pour le langage Oktopios — modeles decores, migrations, query-builder (facon Doctrine / Django ORM)
5
5
  Author: Mouanwiya Ali Soule
6
6
  License: MIT License
@@ -31,7 +31,7 @@ Keywords: oktopios,orm,database,sqlite,migrations,okp
31
31
  Requires-Python: >=3.8
32
32
  Description-Content-Type: text/markdown
33
33
  License-File: LICENSE
34
- Requires-Dist: oktopios>=0.7.0
34
+ Requires-Dist: oktopios>=0.16.0
35
35
  Dynamic: license-file
36
36
 
37
37
  # oktopios-orm 🐙🗄️
@@ -100,13 +100,51 @@ Exécuter : `okp examples/blog.okp`
100
100
  - **`Query`** — constructeur de requêtes fluide : `select().where().orderBy().get()`,
101
101
  paramétré (anti-injection).
102
102
 
103
+ ## Relations `@ManyToOne` 🔗
104
+
105
+ ```okp
106
+ @Entity("auteurs")
107
+ class Auteur { @Id var id: int @Column("nom") var nom: string }
108
+
109
+ @Entity("articles")
110
+ class Article {
111
+ @Id var id: int
112
+ @Column("titre") var titre: string
113
+ @ManyToOne("Auteur") var auteur: any // colonne FK : auteur_id
114
+ }
115
+
116
+ var repoA = new Repo(db, new Auteur())
117
+ var a = new Auteur(); a.nom = "Awa"; repoA.save(a) // save réaffecte a.id
118
+
119
+ var repoArt = new Repo(db, new Article())
120
+ var art = new Article(); art.titre = "Hello"; art.auteur = a
121
+ repoArt.save(art) // écrit auteur_id = a.id
122
+
123
+ var trouve = repoArt.find(1)
124
+ print(trouve.auteur.nom) // -> "Awa" (objet lié chargé)
125
+ ```
126
+
127
+ `@ManyToOne("Classe")` crée une colonne de clé étrangère `<champ>_id` (ou le 2ᵉ
128
+ argument), écrite par `save` et chargée par `find`/`findBy` (un niveau).
129
+
130
+ ## Pagination 📄
131
+
132
+ ```okp
133
+ print(repoArt.count()) // nombre total de lignes
134
+ for (x in repoArt.page(10, 2)) { // page 2, 10 par page (entités hydratées)
135
+ print(x.titre)
136
+ }
137
+ // Bas niveau : Query.limit(n).offset(d) + Query.count()
138
+ ```
139
+
103
140
  ## Décorateurs reconnus
104
141
 
105
142
  | Décorateur | Cible | Effet |
106
143
  |---|---|---|
107
144
  | `@Entity("table")` | classe | nom de la table |
108
145
  | `@Column("colonne")` | champ | nom de la colonne |
109
- | `@Id` | champ | clé primaire |
146
+ | `@Id` | champ | clé primaire (auto-générée, réaffectée par `save`) |
147
+ | `@ManyToOne("Classe", "fk"?)` | champ | relation vers une autre entité |
110
148
 
111
149
  ## Licence
112
150
 
@@ -7,4 +7,5 @@ oktopios_orm.egg-info/PKG-INFO
7
7
  oktopios_orm.egg-info/SOURCES.txt
8
8
  oktopios_orm.egg-info/dependency_links.txt
9
9
  oktopios_orm.egg-info/requires.txt
10
- oktopios_orm.egg-info/top_level.txt
10
+ oktopios_orm.egg-info/top_level.txt
11
+ tests/test_orm.py
@@ -0,0 +1 @@
1
+ oktopios>=0.16.0
@@ -4,14 +4,14 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "oktopios-orm"
7
- version = "0.1.0"
7
+ version = "0.3.0"
8
8
  description = "ORM pour le langage Oktopios — modeles decores, migrations, query-builder (facon Doctrine / Django ORM)"
9
9
  readme = "README.md"
10
10
  license = { file = "LICENSE" }
11
11
  requires-python = ">=3.8"
12
12
  authors = [{ name = "Mouanwiya Ali Soule" }]
13
13
  keywords = ["oktopios", "orm", "database", "sqlite", "migrations", "okp"]
14
- dependencies = ["oktopios>=0.7.0"]
14
+ dependencies = ["oktopios>=0.16.0"]
15
15
 
16
16
  [project.urls]
17
17
  Homepage = "https://github.com/ALISOULEMOUANWIYA/oktopios-orm"
@@ -0,0 +1,158 @@
1
+ """
2
+ Tests d'intégration de l'ORM (oktopios-orm).
3
+
4
+ Exécute un vrai programme Oktopios qui migre une base SQLite temporaire, insère
5
+ des entités via `Repo.save`, puis relit via `all` / `findBy`. Vérifie :
6
+ - la clé primaire est auto-générée (ids 1 et 2) ;
7
+ - `save` renvoie le nouvel id ;
8
+ - l'hydratation reconstruit des objets indexables (`findBy(...)[0]`).
9
+
10
+ En dev (dépôts frères côte à côte) les sources de `oktopios` (../version.0.0.1)
11
+ sont ajoutées au PYTHONPATH ; en CI on compte sur les paquets installés.
12
+ """
13
+ import os
14
+ import subprocess
15
+ import sys
16
+
17
+ import pytest
18
+
19
+ REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
20
+
21
+
22
+ def _child_env():
23
+ env = dict(os.environ)
24
+ extra = [REPO_ROOT] # pour que `use "oktopios_orm/orm.okp"` résolve via cwd
25
+ parent = os.path.dirname(REPO_ROOT)
26
+ lang = os.path.join(parent, "version.0.0.1")
27
+ if os.path.isdir(lang):
28
+ extra.append(lang)
29
+ env["PYTHONPATH"] = os.pathsep.join(extra + [env.get("PYTHONPATH", "")])
30
+ env["PYTHONIOENCODING"] = "utf-8"
31
+ return env
32
+
33
+
34
+ PROG = '''use "oktopios_orm/orm.okp"
35
+
36
+ @Entity("articles")
37
+ class Article {{
38
+ @Id
39
+ var id: int
40
+ @Column("titre")
41
+ var titre: string
42
+ @Column("contenu")
43
+ var contenu: string
44
+ }}
45
+
46
+ var db = "{db}"
47
+ var schema = new Schema()
48
+ schema.migrate(db, new Article())
49
+ var repo = new Repo(db, new Article())
50
+
51
+ var a = new Article()
52
+ a.titre = "Bonjour"
53
+ a.contenu = "Premier"
54
+ print("save1=" + repo.save(a))
55
+
56
+ var b = new Article()
57
+ b.titre = "Oktopios"
58
+ b.contenu = "Deuxieme"
59
+ print("save2=" + repo.save(b))
60
+
61
+ var tous = repo.all()
62
+ var n = 0
63
+ for (x in tous) {{ n = n + 1 }}
64
+ print("count=" + n)
65
+
66
+ var trouves = repo.findBy("titre", "Oktopios")
67
+ print("found=" + trouves[0].contenu)
68
+ '''
69
+
70
+
71
+ def _run_okp(source, tmp_path):
72
+ app = tmp_path / "prog.okp"
73
+ app.write_text(source, encoding="utf-8")
74
+ proc = subprocess.run(
75
+ [sys.executable, "-m", "vm.main", str(app)],
76
+ cwd=REPO_ROOT, env=_child_env(),
77
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=60,
78
+ )
79
+ return proc.stdout.decode("utf-8", "replace")
80
+
81
+
82
+ def test_orm_crud_and_autoincrement(tmp_path):
83
+ db = str(tmp_path / "t.db").replace("\\", "/")
84
+ out = _run_okp(PROG.format(db=db), tmp_path)
85
+ assert "save1=1" in out, out
86
+ assert "save2=2" in out, out # clé primaire auto-générée
87
+ assert "count=2" in out, out
88
+ assert "found=Deuxieme" in out, out # hydratation + findBy(...)[0] indexable
89
+
90
+
91
+ PROG_REL = '''use "oktopios_orm/orm.okp"
92
+
93
+ @Entity("auteurs")
94
+ class Auteur {{
95
+ @Id
96
+ var id: int
97
+ @Column("nom")
98
+ var nom: string
99
+ }}
100
+
101
+ @Entity("articles")
102
+ class Article {{
103
+ @Id
104
+ var id: int
105
+ @Column("titre")
106
+ var titre: string
107
+ @ManyToOne("Auteur")
108
+ var auteur: any
109
+ }}
110
+
111
+ var db = "{db}"
112
+ var schema = new Schema()
113
+ schema.migrate(db, new Auteur())
114
+ schema.migrate(db, new Article())
115
+
116
+ var repoA = new Repo(db, new Auteur())
117
+ var a1 = new Auteur()
118
+ a1.nom = "Awa"
119
+ repoA.save(a1)
120
+ print("auteurId=" + a1.id)
121
+
122
+ var repoArt = new Repo(db, new Article())
123
+ var art1 = new Article()
124
+ art1.titre = "Premier"
125
+ art1.auteur = a1
126
+ repoArt.save(art1)
127
+ var art2 = new Article()
128
+ art2.titre = "Deuxieme"
129
+ art2.auteur = a1
130
+ repoArt.save(art2)
131
+ var art3 = new Article()
132
+ art3.titre = "Troisieme"
133
+ art3.auteur = a1
134
+ repoArt.save(art3)
135
+
136
+ var trouve = repoArt.find(1)
137
+ print("rel=" + trouve.titre + "/" + trouve.auteur.nom)
138
+ print("count=" + repoArt.count())
139
+
140
+ var p1 = repoArt.page(2, 1)
141
+ var n1 = 0
142
+ for (x in p1) {{ n1 = n1 + 1 }}
143
+ print("page1=" + n1)
144
+ var p2 = repoArt.page(2, 2)
145
+ var n2 = 0
146
+ for (x in p2) {{ n2 = n2 + 1 }}
147
+ print("page2=" + n2)
148
+ '''
149
+
150
+
151
+ def test_orm_relations_and_pagination(tmp_path):
152
+ db = str(tmp_path / "r.db").replace("\\", "/")
153
+ out = _run_okp(PROG_REL.format(db=db), tmp_path)
154
+ assert "auteurId=1" in out, out # save réaffecte l'@Id
155
+ assert "rel=Premier/Awa" in out, out # @ManyToOne hydraté
156
+ assert "count=3" in out, out
157
+ assert "page1=2" in out, out # pagination LIMIT/OFFSET
158
+ assert "page2=1" in out, out
@@ -1,179 +0,0 @@
1
- // =====================================================================
2
- // oktopios-framework — Couche ORM
3
- // Écrit EN Oktopios, s'appuie sur la réflexion et les décorateurs du
4
- // langage (>= 0.6.0). Chargé via : use "framework/orm.okp"
5
- //
6
- // - Schema : migrations (génère le schéma SQL depuis les modèles décorés)
7
- // - Repo : dépôt générique (save / all / findBy / remove + hydratation)
8
- // - Query : constructeur de requêtes fluide
9
- //
10
- // Décorateurs reconnus :
11
- // @Entity("table") (classe) -> nom de table
12
- // @Column("colonne") (champ) -> nom de colonne
13
- // @Id (champ) -> clé primaire
14
- // =====================================================================
15
- inject Type
16
- inject DataImport
17
-
18
- // ---------------------------------------------------------------------
19
- // Schema — génération de schéma / migrations
20
- // ---------------------------------------------------------------------
21
- class Schema {
22
- fun sqlType(t: string): string {
23
- if (t == "int") { return "INTEGER" }
24
- if (t == "float") { return "REAL" }
25
- if (t == "bool") { return "INTEGER" }
26
- return "TEXT"
27
- }
28
-
29
- fun tableName(entity: any): string {
30
- var e = Type.annotation(entity, "Entity")
31
- if (e != null) { return e[0] }
32
- return Type.className(entity)
33
- }
34
-
35
- fun columnName(entity: any, champ: string): string {
36
- var c = Type.fieldAnnotation(entity, champ, "Column")
37
- if (c != null) { return c[0] }
38
- return champ
39
- }
40
-
41
- fun idField(entity: any): string {
42
- for (f in Type.fields(entity)) {
43
- if (Type.fieldAnnotation(entity, f, "Id") != null) { return f }
44
- }
45
- return "id"
46
- }
47
-
48
- fun createTableSQL(entity: any): string {
49
- var defs = ""
50
- for (f in Type.fields(entity)) {
51
- if (defs != "") { defs = defs + ", " }
52
- var ligne = this.columnName(entity, f) + " " + this.sqlType(Type.fieldType(entity, f))
53
- if (Type.fieldAnnotation(entity, f, "Id") != null) {
54
- ligne = ligne + " PRIMARY KEY"
55
- }
56
- defs = defs + ligne
57
- }
58
- return "CREATE TABLE IF NOT EXISTS " + this.tableName(entity) + " (" + defs + ")"
59
- }
60
-
61
- // Crée la table dans la base à partir d'un exemple d'entité (modèle décoré)
62
- fun migrate(db: string, entity: any): string {
63
- var sql = this.createTableSQL(entity)
64
- DataImport.execSQL(db, sql, [])
65
- return sql
66
- }
67
- }
68
-
69
- // ---------------------------------------------------------------------
70
- // Repo — dépôt de données générique pour un modèle
71
- // ---------------------------------------------------------------------
72
- class Repo {
73
- var db: string
74
- var table: string
75
- var model: string
76
- var schema: Schema
77
-
78
- // `sample` : une instance du modèle, utilisée pour lire les métadonnées
79
- fun __construct(db: string, sample: any) {
80
- this.db = db
81
- this.schema = new Schema()
82
- this.table = this.schema.tableName(sample)
83
- this.model = Type.className(sample)
84
- }
85
-
86
- fun save(entity: any): int {
87
- var colonnes = ""
88
- var marques = ""
89
- var valeurs = []
90
- for (f in Type.fields(entity)) {
91
- if (colonnes != "") {
92
- colonnes = colonnes + ", "
93
- marques = marques + ", "
94
- }
95
- colonnes = colonnes + this.schema.columnName(entity, f)
96
- marques = marques + "?"
97
- valeurs = valeurs + [Type.get(entity, f)]
98
- }
99
- var sql = "INSERT INTO " + this.table + " (" + colonnes + ") VALUES (" + marques + ")"
100
- return DataImport.execSQL(this.db, sql, valeurs)
101
- }
102
-
103
- // Transforme les lignes SQL (colonnes) en instances du modèle (champs)
104
- fun hydrate(lignes: any): any {
105
- var objets = []
106
- for (ligne in lignes) {
107
- var obj = Type.create(this.model)
108
- for (f in Type.fields(obj)) {
109
- var col = this.schema.columnName(obj, f)
110
- Type.set(obj, f, ligne[col])
111
- }
112
- objets = objets + [obj]
113
- }
114
- return objets
115
- }
116
-
117
- fun all(): any {
118
- return this.hydrate(DataImport.execSQL(this.db, "SELECT * FROM " + this.table, []))
119
- }
120
-
121
- fun findBy(colonne: string, valeur: any): any {
122
- var sql = "SELECT * FROM " + this.table + " WHERE " + colonne + " = ?"
123
- return this.hydrate(DataImport.execSQL(this.db, sql, [valeur]))
124
- }
125
-
126
- fun remove(colonne: string, valeur: any): int {
127
- var sql = "DELETE FROM " + this.table + " WHERE " + colonne + " = ?"
128
- return DataImport.execSQL(this.db, sql, [valeur])
129
- }
130
- }
131
-
132
- // ---------------------------------------------------------------------
133
- // Query — constructeur de requêtes fluide
134
- // ---------------------------------------------------------------------
135
- class Query {
136
- var db: string
137
- var table: string
138
- var champs: string
139
- var conds: string
140
- var params: any
141
- var ordre: string
142
-
143
- fun __construct(db: string, table: string) {
144
- this.db = db
145
- this.table = table
146
- this.champs = "*"
147
- this.conds = ""
148
- this.params = []
149
- this.ordre = ""
150
- }
151
-
152
- fun select(champs: string): Query {
153
- this.champs = champs
154
- return this
155
- }
156
-
157
- fun where(colonne: string, op: string, valeur: any): Query {
158
- if (this.conds != "") { this.conds = this.conds + " AND " }
159
- this.conds = this.conds + colonne + " " + op + " ?"
160
- this.params = this.params + [valeur]
161
- return this
162
- }
163
-
164
- fun orderBy(colonne: string, sens: string): Query {
165
- this.ordre = " ORDER BY " + colonne + " " + sens
166
- return this
167
- }
168
-
169
- fun sql(): string {
170
- var s = "SELECT " + this.champs + " FROM " + this.table
171
- if (this.conds != "") { s = s + " WHERE " + this.conds }
172
- s = s + this.ordre
173
- return s
174
- }
175
-
176
- fun get(): any {
177
- return DataImport.execSQL(this.db, this.sql(), this.params)
178
- }
179
- }
@@ -1 +0,0 @@
1
- oktopios>=0.7.0
File without changes
File without changes