streamby-core 0.24.0 → 0.24.2

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.
@@ -44,8 +44,9 @@ exports.getConnection = getConnection;
44
44
  const ensureTablesExist = async (pool) => {
45
45
  try {
46
46
  await pool.query(`
47
+ CREATE SCHEMA IF NOT EXISTS streamby;
47
48
  CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
48
- CREATE TABLE IF NOT EXISTS projects (
49
+ CREATE TABLE IF NOT EXISTS streamby.projects (
49
50
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
50
51
  name VARCHAR(255) NOT NULL,
51
52
  description TEXT,
@@ -57,21 +58,21 @@ const ensureTablesExist = async (pool) => {
57
58
  console.log('✅ "projects" table ensured to exist.');
58
59
  // Ensure dbType column exists and is correctly configured
59
60
  await pool.query(`
60
- ALTER TABLE projects ADD COLUMN IF NOT EXISTS "dbType" VARCHAR(50);
61
+ ALTER TABLE streamby.projects ADD COLUMN IF NOT EXISTS "dbType" VARCHAR(50);
61
62
  `);
62
63
  await pool.query(`
63
- UPDATE projects SET "dbType" = 'nosql' WHERE "dbType" IS NULL;
64
+ UPDATE streamby.projects SET "dbType" = 'nosql' WHERE "dbType" IS NULL;
64
65
  `);
65
66
  await pool.query(`
66
- ALTER TABLE projects ALTER COLUMN "dbType" SET NOT NULL;
67
+ ALTER TABLE streamby.projects ALTER COLUMN "dbType" SET NOT NULL;
67
68
  `);
68
69
  await pool.query(`
69
- ALTER TABLE projects ALTER COLUMN "dbType" SET DEFAULT 'nosql';
70
+ ALTER TABLE streamby.projects ALTER COLUMN "dbType" SET DEFAULT 'nosql';
70
71
  `);
71
72
  await pool.query(`
72
- CREATE TABLE IF NOT EXISTS exports (
73
+ CREATE TABLE IF NOT EXISTS streamby.exports (
73
74
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
74
- "projectId" UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
75
+ "projectId" UUID NOT NULL REFERENCES streamby.projects(id) ON DELETE CASCADE,
75
76
  status VARCHAR(50) NOT NULL DEFAULT 'pending',
76
77
  "filePath" TEXT,
77
78
  "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
@@ -80,9 +81,9 @@ const ensureTablesExist = async (pool) => {
80
81
  `);
81
82
  console.log('✅ "exports" table ensured to exist.');
82
83
  await pool.query(`
83
- CREATE TABLE IF NOT EXISTS project_members (
84
+ CREATE TABLE IF NOT EXISTS streamby.project_members (
84
85
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
85
- "projectId" UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
86
+ "projectId" UUID NOT NULL REFERENCES streamby.projects(id) ON DELETE CASCADE,
86
87
  "userId" VARCHAR(255) NOT NULL,
87
88
  role VARCHAR(255) NOT NULL DEFAULT 'member',
88
89
  archived BOOLEAN NOT NULL DEFAULT FALSE,
@@ -9,9 +9,9 @@ export declare const createSQLRawExportTable: (connection: Pool, projectId: stri
9
9
  exportId: string;
10
10
  }>;
11
11
  export declare const sqlAdapter: {
12
- find: (connection: Pool, tableName: string, filter: any) => Promise<any[]>;
13
- findOne: (connection: Pool, tableName: string, filter: any) => Promise<any | null>;
14
- create: (connection: Pool, tableName: string, data: any) => Promise<any>;
15
- update: (connection: Pool, tableName: string, filter: any, data: any) => Promise<any | null>;
16
- delete: (connection: Pool, tableName: string, filter: any) => Promise<number>;
12
+ find: (connection: Pool, tableName: string, filter: any, schema?: string) => Promise<any[]>;
13
+ findOne: (connection: Pool, tableName: string, filter: any, schema?: string) => Promise<any | null>;
14
+ create: (connection: Pool, tableName: string, data: any, schema?: string) => Promise<any>;
15
+ update: (connection: Pool, tableName: string, filter: any, data: any, schema?: string) => Promise<any | null>;
16
+ delete: (connection: Pool, tableName: string, filter: any, schema?: string) => Promise<number>;
17
17
  };
@@ -44,45 +44,50 @@ const createSQLRawExportTable = async (connection, projectId, exportName, jsonDa
44
44
  };
45
45
  exports.createSQLRawExportTable = createSQLRawExportTable;
46
46
  exports.sqlAdapter = {
47
- find: async (connection, tableName, filter) => {
47
+ find: async (connection, tableName, filter, schema) => {
48
48
  const keys = Object.keys(filter);
49
49
  const values = Object.values(filter);
50
- let query = `SELECT * FROM "${tableName}"`;
50
+ const fullTableName = schema ? `"${schema}"."${tableName}"` : `"${tableName}"`;
51
+ let query = `SELECT * FROM ${fullTableName}`;
51
52
  if (keys.length > 0) {
52
- const where = keys.map((key, i) => `"${key}" = $${i + 1}`).join(' AND ');
53
+ const where = keys.map((key, i) => `"${key}" = ${i + 1}`).join(' AND ');
53
54
  query += ` WHERE ${where}`;
54
55
  }
55
56
  const result = await connection.query(query, values);
56
57
  return result.rows;
57
58
  },
58
- findOne: async (connection, tableName, filter) => {
59
+ findOne: async (connection, tableName, filter, schema) => {
59
60
  const keys = Object.keys(filter);
60
61
  const values = Object.values(filter);
61
- const where = keys.map((key, i) => `"${key}" = $${i + 1}`).join(' AND ');
62
- const result = await connection.query(`SELECT * FROM "${tableName}" WHERE ${where} LIMIT 1`, values);
62
+ const where = keys.map((key, i) => `"${key}" = ${i + 1}`).join(' AND ');
63
+ const fullTableName = schema ? `"${schema}"."${tableName}"` : `"${tableName}"`;
64
+ const result = await connection.query(`SELECT * FROM ${fullTableName} WHERE ${where} LIMIT 1`, values);
63
65
  return result.rows[0] || null;
64
66
  },
65
- create: async (connection, tableName, data) => {
67
+ create: async (connection, tableName, data, schema) => {
66
68
  const keys = Object.keys(data).map(key => `"${key}"`).join(', ');
67
69
  const values = Object.values(data);
68
- const placeholders = values.map((_, i) => `$${i + 1}`).join(', ');
69
- const result = await connection.query(`INSERT INTO "${tableName}" (${keys}) VALUES (${placeholders}) RETURNING *`, values);
70
+ const placeholders = values.map((_, i) => `${i + 1}`).join(', ');
71
+ const fullTableName = schema ? `"${schema}"."${tableName}"` : `"${tableName}"`;
72
+ const result = await connection.query(`INSERT INTO ${fullTableName} (${keys}) VALUES (${placeholders}) RETURNING *`, values);
70
73
  return result.rows[0];
71
74
  },
72
- update: async (connection, tableName, filter, data) => {
75
+ update: async (connection, tableName, filter, data, schema) => {
73
76
  const dataKeys = Object.keys(data);
74
77
  const filterKeys = Object.keys(filter);
75
78
  const values = [...Object.values(data), ...Object.values(filter)];
76
- const setClause = dataKeys.map((key, i) => `"${key}" = $${i + 1}`).join(', ');
77
- const whereClause = filterKeys.map((key, i) => `"${key}" = $${dataKeys.length + i + 1}`).join(' AND ');
78
- const result = await connection.query(`UPDATE "${tableName}" SET ${setClause} WHERE ${whereClause} RETURNING *`, values);
79
+ const setClause = dataKeys.map((key, i) => `"${key}" = ${i + 1}`).join(', ');
80
+ const whereClause = filterKeys.map((key, i) => `"${key}" = ${dataKeys.length + i + 1}`).join(' AND ');
81
+ const fullTableName = schema ? `"${schema}"."${tableName}"` : `"${tableName}"`;
82
+ const result = await connection.query(`UPDATE ${fullTableName} SET ${setClause} WHERE ${whereClause} RETURNING *`, values);
79
83
  return result.rows[0] || null;
80
84
  },
81
- delete: async (connection, tableName, filter) => {
85
+ delete: async (connection, tableName, filter, schema) => {
82
86
  const keys = Object.keys(filter);
83
87
  const values = Object.values(filter);
84
- const where = keys.map((key, i) => `"${key}" = $${i + 1}`).join(' AND ');
85
- const result = await connection.query(`DELETE FROM "${tableName}" WHERE ${where}`, values);
88
+ const where = keys.map((key, i) => `"${key}" = ${i + 1}`).join(' AND ');
89
+ const fullTableName = schema ? `"${schema}"."${tableName}"` : `"${tableName}"`;
90
+ const result = await connection.query(`DELETE FROM ${fullTableName} WHERE ${where}`, values);
86
91
  return result.rowCount || 0;
87
92
  },
88
93
  };
@@ -20,11 +20,13 @@ function createStreamByRouter(config) {
20
20
  const adapter = config.adapter || (0, storage_1.createStorageProvider)(config.storageProviders);
21
21
  if (config.databases) {
22
22
  const allDbIds = config.databases.map(db => db.id);
23
- (0, manager_1.registerModel)('projects', allDbIds, 'projects');
24
- (0, manager_1.registerModel)('exports', allDbIds, 'exports');
23
+ const sqlDbs = config.databases.filter(db => db.type === 'sql');
24
+ const streambySchema = sqlDbs.length > 0 ? 'streamby' : undefined;
25
+ (0, manager_1.registerModel)('projects', allDbIds, 'projects', streambySchema);
26
+ (0, manager_1.registerModel)('exports', allDbIds, 'exports', streambySchema);
25
27
  const mainDb = config.databases.find(db => db.main);
26
28
  if (mainDb) {
27
- (0, manager_1.registerModel)('users', [mainDb.id], 'users');
29
+ (0, manager_1.registerModel)('users', [mainDb.id], 'users', streambySchema);
28
30
  }
29
31
  }
30
32
  router.use((0, auth_2.authenticate)(config));
@@ -80,6 +80,7 @@ function projectRouter(config) {
80
80
  res.status(200).json({ success: true, projects: projects, projectId: newProject._id || newProject.id, message: 'Project created successfully' });
81
81
  }
82
82
  catch (err) {
83
+ console.error('Error creating project:', err);
83
84
  res.status(500).json({ message: 'Failed to create project', details: err.message });
84
85
  }
85
86
  });
@@ -2,7 +2,10 @@ import { Document } from 'mongodb';
2
2
  export declare class Model<T extends Document> {
3
3
  private connectionIds;
4
4
  private tableName;
5
- constructor(connectionIds: string[], tableName: string);
5
+ private schema?;
6
+ constructor(connectionIds: string[], tableName: string, schema?: string);
7
+ getConnectionIds(): string[];
8
+ getTableName(): string;
6
9
  useDbType(dbType: string): Model<T>;
7
10
  find(filter: any): Promise<T[]>;
8
11
  private transformResult;
@@ -6,9 +6,17 @@ const mongodb_1 = require("mongodb");
6
6
  const sql_1 = require("../adapters/database/sql");
7
7
  const nosql_1 = require("../adapters/database/nosql");
8
8
  class Model {
9
- constructor(connectionIds, tableName) {
9
+ constructor(connectionIds, tableName, schema) {
10
10
  this.connectionIds = connectionIds;
11
11
  this.tableName = tableName;
12
+ this.schema = schema;
13
+ }
14
+ // Add these getter methods
15
+ getConnectionIds() {
16
+ return this.connectionIds;
17
+ }
18
+ getTableName() {
19
+ return this.tableName;
12
20
  }
13
21
  useDbType(dbType) {
14
22
  const filteredConnectionIds = this.connectionIds.filter(id => {
@@ -34,10 +42,11 @@ class Model {
34
42
  if (this.tableName === 'projects' && processedFilter.members && processedFilter.members.$elemMatch) {
35
43
  // Handle members filter for SQL projects
36
44
  const userId = processedFilter.members.$elemMatch.userId;
45
+ const schema = this.schema || 'streamby'; // Default to 'streamby' if schema not provided
37
46
  const query = `
38
47
  SELECT p.*, pm."userId" as memberUserId, pm.archived as memberArchived
39
- FROM "projects" p
40
- JOIN "project_members" pm ON p.id = pm."projectId"
48
+ FROM "${schema}"."projects" p
49
+ JOIN "${schema}"."project_members" pm ON p.id = pm."projectId"
41
50
  WHERE pm."userId" = $1
42
51
  `;
43
52
  const result = await connection.query(query, [userId]);
@@ -52,13 +61,13 @@ class Model {
52
61
  }
53
62
  else {
54
63
  // General SQL find
55
- sqlResults = await sql_1.sqlAdapter.find(connection, this.tableName, processedFilter);
64
+ sqlResults = await sql_1.sqlAdapter.find(connection, this.tableName, processedFilter, this.schema);
56
65
  }
57
66
  for (const item of sqlResults) {
58
67
  const transformedItem = this.transformResult(item);
59
68
  if (this.tableName === 'projects' && !transformedItem.members) {
60
69
  // For projects, if members not already populated by join, fetch from project_members table
61
- const projectMembers = await sql_1.sqlAdapter.find(connection, 'project_members', { projectId: transformedItem.id });
70
+ const projectMembers = await sql_1.sqlAdapter.find(connection, 'project_members', { projectId: transformedItem.id }, this.schema);
62
71
  transformedItem.members = projectMembers.map((member) => ({
63
72
  userId: member.userId,
64
73
  role: member.role, // Assuming role is also stored in project_members
@@ -96,12 +105,19 @@ class Model {
96
105
  processedFilter.id = processedFilter._id;
97
106
  delete processedFilter._id;
98
107
  }
99
- const result = await sql_1.sqlAdapter.findOne(connection, this.tableName, processedFilter);
108
+ // Special handling for 'users' table with raw query
109
+ if (this.tableName === 'users' && processedFilter.id) {
110
+ const schema = this.schema || 'streamby'; // Default to 'streamby' if schema not provided
111
+ const query = `SELECT * FROM "${schema}"."${this.tableName}" WHERE "id" = $1::uuid LIMIT 1`;
112
+ const result = await connection.query(query, [processedFilter.id]);
113
+ return result.rows[0] || null;
114
+ }
115
+ const result = await sql_1.sqlAdapter.findOne(connection, this.tableName, processedFilter, this.schema); // Pass this.schema
100
116
  if (result) {
101
117
  const transformedResult = this.transformResult(result);
102
118
  if (this.tableName === 'projects') {
103
119
  // For projects, fetch members from project_members table
104
- const projectMembers = await sql_1.sqlAdapter.find(connection, 'project_members', { projectId: transformedResult.id });
120
+ const projectMembers = await sql_1.sqlAdapter.find(connection, 'project_members', { projectId: transformedResult.id }, this.schema);
105
121
  transformedResult.members = projectMembers.map((member) => ({
106
122
  userId: member.userId,
107
123
  role: member.role, // Assuming role is also stored in project_members
@@ -156,7 +172,7 @@ class Model {
156
172
  dataToInsert[key] = data[key];
157
173
  }
158
174
  }
159
- const created = await sql_1.sqlAdapter.create(connection, this.tableName, dataToInsert);
175
+ const created = await sql_1.sqlAdapter.create(connection, this.tableName, dataToInsert, this.schema);
160
176
  // Insert members into project_members table for SQL
161
177
  if (this.tableName === 'projects' && membersToInsert.length > 0) {
162
178
  for (const member of membersToInsert) {
@@ -165,7 +181,7 @@ class Model {
165
181
  userId: member.userId,
166
182
  role: member.role,
167
183
  archived: member.archived || false,
168
- });
184
+ }, this.schema);
169
185
  }
170
186
  }
171
187
  return created;
@@ -221,7 +237,7 @@ class Model {
221
237
  if (dbType === 'sql') {
222
238
  // For SQL, directly update the project_members table
223
239
  const memberUpdateResult = await sql_1.sqlAdapter.update(connection, 'project_members', { projectId: originalProjectId, userId: userIdToUpdate }, // originalProjectId is fine for SQL
224
- { archived: newArchivedStatus, archivedBy: archivedBy, archivedAt: archivedAt });
240
+ { archived: newArchivedStatus, archivedBy: archivedBy, archivedAt: archivedAt }, this.schema);
225
241
  // After updating the member, fetch the full project to return
226
242
  if (memberUpdateResult) {
227
243
  const updatedProject = await this.findOne({ _id: originalProjectId });
@@ -252,7 +268,7 @@ class Model {
252
268
  // General update logic
253
269
  // Use the correctly constructed updateFilter
254
270
  if (dbType === 'sql') {
255
- const result = await sql_1.sqlAdapter.update(connection, this.tableName, updateFilter, data);
271
+ const result = await sql_1.sqlAdapter.update(connection, this.tableName, updateFilter, data, this.schema);
256
272
  if (result)
257
273
  return result;
258
274
  }
@@ -278,7 +294,7 @@ class Model {
278
294
  delete processedFilter._id;
279
295
  }
280
296
  console.log(`SQL: Deleting from ${this.tableName} with filter:`, processedFilter);
281
- const count = await sql_1.sqlAdapter.delete(connection, this.tableName, processedFilter);
297
+ const count = await sql_1.sqlAdapter.delete(connection, this.tableName, processedFilter, this.schema);
282
298
  console.log(`SQL: Deleted ${count} rows from ${this.tableName}`);
283
299
  deletedCount += count;
284
300
  }
@@ -1 +1 @@
1
- export declare const registerModel: (name: string, connectionIds: string[], tableName: string) => void;
1
+ export declare const registerModel: (name: string, connectionIds: string[], tableName: string, schema?: string) => void;
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.registerModel = void 0;
4
4
  const registry_1 = require("./registry");
5
- const registerModel = (name, connectionIds, tableName) => {
6
- (0, registry_1.defineModel)(name, connectionIds, tableName);
5
+ const registerModel = (name, connectionIds, tableName, schema) => {
6
+ (0, registry_1.defineModel)(name, connectionIds, tableName, schema);
7
7
  };
8
8
  exports.registerModel = registerModel;
@@ -1,3 +1,3 @@
1
1
  import { Model } from './Model';
2
- export declare const defineModel: (name: string, connectionIds: string[], tableName: string) => void;
2
+ export declare const defineModel: (name: string, connectionIds: string[], tableName: string, schema?: string) => void;
3
3
  export declare const getModel: (name: string, dbType?: string) => Model<any>;
@@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getModel = exports.defineModel = void 0;
4
4
  const Model_1 = require("./Model");
5
5
  const models = {};
6
- const defineModel = (name, connectionIds, tableName) => {
7
- models[name] = new Model_1.Model(connectionIds, tableName);
6
+ const defineModel = (name, connectionIds, tableName, schema) => {
7
+ models[name] = new Model_1.Model(connectionIds, tableName, schema);
8
8
  };
9
9
  exports.defineModel = defineModel;
10
10
  const getModel = (name, dbType) => {
package/dist/pg/setup.js CHANGED
@@ -32,7 +32,7 @@ async function setupStreambyPg({ pool, schema = 'streamby', reset = false, allow
32
32
  // Read and append reset SQL if reset is true
33
33
  if (reset) {
34
34
  console.log(`[StreamByPgSetup] Resetting schema "${schema}"...`);
35
- const resetSqlPath = (0, node_path_1.join)(__dirname, '../../sql/reset.sql');
35
+ const resetSqlPath = (0, node_path_1.join)(process.cwd(), 'src/sql/reset.sql');
36
36
  const resetSql = await node_fs_1.promises.readFile(resetSqlPath, 'utf8');
37
37
  fullSql += resetSql;
38
38
  result.didReset = true;
@@ -46,7 +46,7 @@ async function setupStreambyPg({ pool, schema = 'streamby', reset = false, allow
46
46
  }
47
47
  // Read and append setup SQL
48
48
  console.log(`[StreamByPgSetup] Creating/updating tables and indexes in schema "${schema}"...`);
49
- const setupSqlPath = (0, node_path_1.join)(__dirname, '../../sql/setup.sql');
49
+ const setupSqlPath = (0, node_path_1.join)(process.cwd(), 'src/sql/setup.sql');
50
50
  const setupSql = await node_fs_1.promises.readFile(setupSqlPath, 'utf8');
51
51
  fullSql += setupSql;
52
52
  result.didCreateTables = true; // Assuming if setup.sql runs, tables are handled
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "streamby-core",
3
- "version": "0.24.0",
3
+ "version": "0.24.2",
4
4
  "description": "StreamBy middleware framework for media storage management",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",