@flumens/models 0.33.0 → 0.34.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.
package/README.md
CHANGED
|
@@ -52,6 +52,8 @@ connection.
|
|
|
52
52
|
|
|
53
53
|
Search includes common and scientific names, five-character genus/species
|
|
54
54
|
shortcuts, optional SQL filters, and a configurable result limit (default 20).
|
|
55
|
+
`language: 'eng'` matches English common names and Latin scientific names, showing the English name when available. `where` still filters the matching rows (for example, by checklist or group).
|
|
56
|
+
Omit `language` for custom language sets: `where: t => eq(t.language_iso, 'lat')` searches only Latin, while `where: t => inArray(t.language_iso, ['eng', 'fra'])` searches only English and French. In this mode `where` also filters the displayed common name. Without either option, all languages are eligible.
|
|
55
57
|
Common names fill the limit first. Results are sorted by match position.
|
|
56
58
|
`fetchSpecies` preserves the common-name-only list behaviour: taxa without a
|
|
57
59
|
name in the requested language are omitted.
|
|
@@ -47,6 +47,7 @@ export declare const taxonColumns: (taxonListsStore: SQLiteStore) => {
|
|
|
47
47
|
}>>>;
|
|
48
48
|
};
|
|
49
49
|
export type SpeciesColumns = TaxaStore['table']['$inferSelect'];
|
|
50
|
+
export type TaxonRow = CamelizeKeys<Omit<TaxaStore['table']['$inferInsert'], 'list_cid'>>;
|
|
50
51
|
export type SearchResult = {
|
|
51
52
|
foundInName: 'scientificName' | 'commonName';
|
|
52
53
|
warehouseId: number;
|
|
@@ -54,26 +55,29 @@ export type SearchResult = {
|
|
|
54
55
|
taxonGroupId: number;
|
|
55
56
|
commonName?: string;
|
|
56
57
|
preferredId?: number;
|
|
58
|
+
externalKey?: string;
|
|
59
|
+
data?: Record<string, unknown>;
|
|
57
60
|
};
|
|
58
61
|
export type SearchOptions = {
|
|
59
62
|
searchPhrase: string;
|
|
60
|
-
language
|
|
63
|
+
/** Common-name language for matching and display alongside scientific names. */
|
|
64
|
+
language?: string;
|
|
61
65
|
maxResults?: number;
|
|
62
66
|
where?: (table: TaxaStore['table']) => SQL;
|
|
63
67
|
};
|
|
64
68
|
type TaxonColumns = ReturnType<typeof taxonColumns>;
|
|
65
69
|
export default class TaxaStore extends SQLiteStore<TaxonColumns> {
|
|
66
|
-
private
|
|
70
|
+
private readonly lists;
|
|
67
71
|
constructor({ taxonListsStore, name, ...options }: Omit<SQLiteStoreOptions<TaxonColumns>, 'columns' | 'extraConf' | 'name'> & {
|
|
68
72
|
name?: string;
|
|
69
73
|
taxonListsStore: SQLiteStore;
|
|
70
74
|
});
|
|
75
|
+
preloadList(cid: string, generatedAt: number, load: () => Promise<TaxonRow[]>): Promise<void>;
|
|
71
76
|
search({ searchPhrase, language, where, maxResults, }: SearchOptions): Promise<SearchResult[]>;
|
|
72
77
|
private searchCommonNames;
|
|
73
78
|
private searchSciNames;
|
|
74
|
-
private normaliseSearchPhrase;
|
|
75
79
|
getCommonNameById(taxaTaxonListId: string | number, language?: string): Promise<string | null>;
|
|
76
|
-
replaceSpecies(listCid: string, species:
|
|
80
|
+
replaceSpecies(listCid: string, species: TaxonRow[]): Promise<void>;
|
|
77
81
|
/**
|
|
78
82
|
* Fetches all species belonging to this list from the local species store.
|
|
79
83
|
* Optionally accepts an additional where clause to further filter results.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__rest as e,__awaiter as t}from"tslib";import{
|
|
1
|
+
import{__rest as e,__awaiter as t}from"tslib";import{eq as i,ne as a,and as n,getTableColumns as o,sql as r,or as s}from"drizzle-orm";import{index as d,primaryKey as l,alias as c,QueryBuilder as _,SQLiteSyncDialect as u,SQLiteInsertBuilder as m,text as x,integer as h}from"drizzle-orm/sqlite-core";import p,{conflictUpdateAllExcept as g,jsonb as f}from"../SQLiteStore.mjs";const y=e=>({id:h().notNull(),list_cid:x().references((()=>e.table.cid),{onDelete:"cascade"}).notNull(),taxon_group_id:h().notNull(),preferred_taxa_taxon_list_id:h(),parent_id:h(),external_key:x(),language_iso:x().notNull(),taxon:x().notNull(),data:f("data").notNull().default({})});function N(e,t){var i;const a="scientificName"===t;return{foundInName:t,warehouseId:e.id,scientificName:a?e.taxon:e.joinedName,commonName:a?e.joinedName:e.taxon,preferredId:e.preferred_taxa_taxon_list_id,taxonGroupId:e.taxon_group_id,externalKey:null!==(i=e.external_key)&&void 0!==i?i:void 0,data:"string"==typeof e.data?JSON.parse(e.data):e.data}}class b extends p{constructor(t){var{taxonListsStore:i,name:a="taxa"}=t,n=e(t,["taxonListsStore","name"]);super(Object.assign(Object.assign({},n),{name:a,columns:y(i),extraConf:e=>({primaryKey:l({columns:[e.id,e.list_cid]}),taxonIndex:d("taxa"===a?"taxon_idx":`${a}_taxon_idx`).on(e.taxon),searchIndex:d(`${a}_search_idx`).on(e.list_cid,e.language_iso,e.id,e.taxon),preferredNameIndex:d(`${a}_preferred_name_idx`).on(e.list_cid,e.preferred_taxa_taxon_list_id,e.language_iso),languageTaxonGroupIndex:d("taxa"===a?"language_iso_taxon_group_id_idx":`${a}_language_iso_taxon_group_id_idx`).on(e.language_iso,e.taxon_group_id)})})),this.lists=i}preloadList(e,i,a){return t(this,void 0,void 0,(function*(){const t=yield this.lists.find(e);if(t&&t.updatedAt>=i)return;const n=yield a();if(!Array.isArray(n)||!n.length)throw new Error(`Empty or invalid checklist: ${e}`);const o=t||{cid:e,id:null,data:{},createdAt:i,updatedAt:0,syncedAt:null};t||(yield this.lists.save(o)),yield this.replaceSpecies(e,n),yield this.lists.save(Object.assign(Object.assign({},o),{updatedAt:i}))}))}search(e){return t(this,arguments,void 0,(function*({searchPhrase:e,language:t,where:o,maxResults:r=20}){if(yield this.ready,!e||""===t||r<=0)return[];const s=e.toLowerCase(),d=(e=>e.replace(/[!%_]/g,"!$&").replace(/[-.*+?^${}()|[\]\\]/g,"_").replace(/\s+/g,"%"))(s),l=null==o?void 0:o(this.table),c=t?i(this.table.language_iso,t):a(this.table.language_iso,"lat"),_=n(c,l),u=yield this.searchCommonNames(d,_,r),m=r-u.length;if(m>0){const e=[`%${d}%`];5===s.length&&e.push(`${d.slice(0,2)}% ${d.slice(2,6)}%`);const i=t?c:_,a=yield this.searchSciNames(e,i,l,m);u.push(...a)}const x=e=>{var t,i;const a=null!==(i=null===(t=e[e.foundInName])||void 0===t?void 0:t.toLowerCase().indexOf(s))&&void 0!==i?i:-1;return a<0?Number.MAX_SAFE_INTEGER:a};return u.sort(((e,t)=>x(e)-x(t)))}))}searchCommonNames(e,a,s){return t(this,void 0,void 0,(function*(){const{table:t}=this,d=c(t,"preferred"),l=(new _).select(Object.assign(Object.assign({},o(t)),{joinedName:r`${d.taxon} as joinedName`})).from(t).leftJoin(d,n(i(d.id,t.preferred_taxa_taxon_list_id),i(d.list_cid,t.list_cid))).where(n(a,r`${t.taxon} LIKE ${`%${e}%`} ESCAPE '!'`)).groupBy(t.id).limit(s);return(yield this.db.query(l.toSQL())).map((e=>N(e,"commonName")))}))}searchSciNames(e,a,d,l){return t(this,void 0,void 0,(function*(){const{table:t}=this,c=(new _).select({taxon:t.taxon,list_cid:t.list_cid,preferred_taxa_taxon_list_id:t.preferred_taxa_taxon_list_id}).from(t).where(a).as("synonym"),u=(new _).select(Object.assign(Object.assign({},o(t)),{joinedName:r`${c.taxon} as joinedName`})).from(t).leftJoin(c,n(i(c.preferred_taxa_taxon_list_id,t.id),i(c.list_cid,t.list_cid))).where(n(i(t.language_iso,"lat"),s(...e.map((e=>r`${t.taxon} LIKE ${e} ESCAPE '!'`))),d)).groupBy(t.id).limit(l);return(yield this.db.query(u.toSQL())).map((e=>N(e,"scientificName")))}))}getCommonNameById(e){return t(this,arguments,void 0,(function*(e,t="eng"){yield this.ready;const a=(new _).select({taxon:this.table.taxon}).from(this.table).where(n(i(this.table.preferred_taxa_taxon_list_id,parseInt(String(e),10)),i(this.table.language_iso,t))).limit(1),[o]=yield this.db.query(a.toSQL());return(null==o?void 0:o.taxon)||null}))}replaceSpecies(e,i){return t(this,void 0,void 0,(function*(){return yield this.ready,this.db.transaction((a=>t(this,void 0,void 0,(function*(){const t=new u;yield a(t.sqlToQuery(r`DELETE FROM ${this.table} WHERE ${this.table.list_cid} = ${e}`));for(let n=0;n<i.length;n+=500){const o=i.slice(n,n+500),r=new m(this.table,{},t).values(o.map((t=>({id:t.id,list_cid:e,taxon_group_id:t.taxonGroupId,preferred_taxa_taxon_list_id:t.preferredTaxaTaxonListId,parent_id:t.parentId,external_key:t.externalKey,language_iso:t.languageIso,taxon:t.taxon,data:t.data})))).onConflictDoUpdate({target:[this.table.id,this.table.list_cid],set:g(this.table,[])});yield a(r.toSQL())}}))))}))}fetchSpecies(e,a,s){return t(this,void 0,void 0,(function*(){yield this.ready;const{table:t}=this,d=c(t,"preferred"),l=(new _).select(Object.assign(Object.assign({},o(t)),{commonName:r`${d.taxon} as commonName`})).from(t).leftJoin(d,n(i(d.preferred_taxa_taxon_list_id,t.id),i(d.list_cid,t.list_cid),i(d.language_iso,a))).where(n(i(t.language_iso,"lat"),i(t.list_cid,e),null==s?void 0:s(t))).groupBy(t.id).orderBy(t.taxon);return(yield this.db.query(l.toSQL())).map((e=>({foundInName:"commonName",warehouseId:e.id,scientificName:e.taxon,commonName:e.commonName,taxonGroupId:e.taxon_group_id,preferredId:e.preferred_taxa_taxon_list_id}))).filter((e=>!!e.commonName))}))}}export{b as default,y as taxonColumns};
|
|
@@ -20,7 +20,11 @@ export default class SQLiteDatabase {
|
|
|
20
20
|
readonly ready: Deferred<boolean>;
|
|
21
21
|
constructor({ name, debug, web }: SQLiteDatabaseOptions);
|
|
22
22
|
init(): Promise<void>;
|
|
23
|
+
private pending;
|
|
24
|
+
private enqueue;
|
|
23
25
|
query<T>({ sql, params }: Query): Promise<T[]>;
|
|
26
|
+
/** Use the supplied run function for every write in the transaction. */
|
|
27
|
+
transaction(work: (run: (statement: Query) => Promise<void>) => Promise<void>): Promise<void>;
|
|
24
28
|
export(): Promise<Blob>;
|
|
25
29
|
import(blob: Blob): Promise<void>;
|
|
26
30
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__awaiter as e}from"tslib";import{defineCustomElements as t}from"jeep-sqlite/loader/index.js";import{SQLiteConnection as
|
|
1
|
+
import{__awaiter as e}from"tslib";import{defineCustomElements as t}from"jeep-sqlite/loader/index.js";import{noop as i}from"lodash";import{SQLiteConnection as o,CapacitorSQLite as n}from"@capacitor-community/sqlite";import{Capacitor as s}from"@capacitor/core";import{Filesystem as r}from"@capacitor/filesystem";import{Deferred as a}from"@flumens/utils";import{formatSqlQuery as l}from"./utils.mjs";class c{static migrateCordova(t){return e(this,void 0,void 0,(function*(){var e;console.log("SQLite: Cordova db migration");const i=new o(n);try{let o;try{o=yield i.getMigratableDbList(t?"Library/LocalDatabase":void 0)}catch(e){console.log("SQLite: err",e.message)}if(!(null===(e=null==o?void 0:o.values)||void 0===e?void 0:e.length))return void console.log("SQLite: no Cordova db to migrate");console.log("SQLite: migrating",o.values),yield i.addSQLiteSuffix(t?"Library/LocalDatabase":void 0,o.values),yield i.deleteOldDatabases(t?"Library/LocalDatabase":void 0,o.values),console.log("SQLite: migrating done",o.values)}catch(e){console.error(e)}yield i.checkConnectionsConsistency(),yield i.closeAllConnections()}))}get db(){return this.connection}constructor({name:e,debug:t,web:i}){this.sqliteConnection=new o(n),this.name="main",this.debug=!1,this.isWeb=!1,this.ready=new a,this.pending=Promise.resolve(),this.name=e||this.name,this.debug=t||this.debug,this.isWeb=i||this.isWeb}init(){return e(this,void 0,void 0,(function*(){if(this.isWeb){t(window);const e=document.createElement("jeep-sqlite");e.setAttribute("autoSave","true"),document.body.appendChild(e),yield customElements.whenDefined("jeep-sqlite"),yield this.sqliteConnection.initWebStore()}yield this.sqliteConnection.checkConnectionsConsistency(),yield this.sqliteConnection.closeAllConnections(),this.connection=yield this.sqliteConnection.createConnection(this.name,!1,"no-encryption",1,!1),yield this.connection.open(),this.ready.resolve(!0)}))}enqueue(t){const o=this.pending.then((()=>e(this,void 0,void 0,(function*(){return yield this.ready,t(this.db)}))));return this.pending=o.then(i,i),o}query({sql:t,params:i}){return this.enqueue((o=>e(this,void 0,void 0,(function*(){const e=yield o.query(t,i).then((e=>e.values||[])).catch((e=>{throw console.error("SQLite query error:",e,{sql:t,params:i}),e}));return this.debug&&(console.groupCollapsed(`💾 SQL: ${t.trimStart().replaceAll(/\n/g," ").replaceAll(/\s+/g," ").substring(0,30)}...`),console.debug(l(t,i||[])),console.groupEnd()),this.isWeb&&!/^\s*select\b/i.test(t)&&(yield this.sqliteConnection.saveToStore(this.name)),e}))))}transaction(t){return this.enqueue((i=>e(this,void 0,void 0,(function*(){yield i.beginTransaction();try{yield t((t=>e(this,[t],void 0,(function*({sql:e,params:t}){yield i.run(e,t,!1)})))),yield i.commitTransaction()}catch(e){throw yield i.rollbackTransaction(),e}this.isWeb&&(yield this.sqliteConnection.saveToStore(this.name))}))))}export(){return e(this,void 0,void 0,(function*(){if(this.isWeb){const{name:e}=this;return new Promise((t=>{indexedDB.open("jeepSqliteStore").onsuccess=function(i){i.target.result.transaction(["databases"],"readwrite").objectStore("databases").get(`${e}SQLite.db`).onsuccess=function(e){const i=new Blob([e.target.result],{type:"application/vnd.sqlite3"});t(i)}}}))}const{url:e}=yield this.db.getUrl();return(yield fetch(s.convertFileSrc(e))).blob()}))}import(t){return e(this,void 0,void 0,(function*(){if(this.isWeb){const e=new Uint8Array(yield t.arrayBuffer()),{name:i}=this;return void new Promise((t=>{indexedDB.open("jeepSqliteStore").onsuccess=function(o){o.target.result.transaction(["databases"],"readwrite").objectStore("databases").put(e,`${i}SQLite.db`,0).onsuccess=()=>t()}}))}const{url:e}=yield this.db.getUrl(),i=yield new Promise((e=>{const i=new FileReader;i.onload=e,i.readAsDataURL(t)})).then((e=>e.target.result));yield r.writeFile({path:e,data:i})}))}}export{c as default};
|