e170472b2bb5ad9a267dbcfebc12f46a90e615c7
[reactos.git] / reactos / dll / win32 / msi / database.c
1 /*
2 * Implementation of the Microsoft Installer (msi.dll)
3 *
4 * Copyright 2002,2003,2004,2005 Mike McCormack for CodeWeavers
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 */
20
21 #include "msipriv.h"
22
23 #include <stdio.h>
24
25 WINE_DEFAULT_DEBUG_CHANNEL(msi);
26
27 /*
28 * .MSI file format
29 *
30 * An .msi file is a structured storage file.
31 * It contains a number of streams.
32 * A stream for each table in the database.
33 * Two streams for the string table in the database.
34 * Any binary data in a table is a reference to a stream.
35 */
36
37 #define IS_INTMSIDBOPEN(x) (((ULONG_PTR)(x) >> 16) == 0)
38
39 static void free_transforms( MSIDATABASE *db )
40 {
41 while( !list_empty( &db->transforms ) )
42 {
43 MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ), MSITRANSFORM, entry );
44 list_remove( &t->entry );
45 IStorage_Release( t->stg );
46 msi_free( t );
47 }
48 }
49
50 static void free_streams( MSIDATABASE *db )
51 {
52 UINT i;
53 for (i = 0; i < db->num_streams; i++)
54 {
55 if (db->streams[i].stream) IStream_Release( db->streams[i].stream );
56 }
57 msi_free( db->streams );
58 }
59
60 void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
61 {
62 MSITRANSFORM *t;
63
64 t = msi_alloc( sizeof *t );
65 t->stg = stg;
66 IStorage_AddRef( stg );
67 list_add_head( &db->transforms, &t->entry );
68 }
69
70 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
71 {
72 MSIDATABASE *db = (MSIDATABASE *) arg;
73
74 msi_free(db->path);
75 free_streams( db );
76 free_cached_tables( db );
77 free_transforms( db );
78 if (db->strings) msi_destroy_stringtable( db->strings );
79 IStorage_Release( db->storage );
80 if (db->deletefile)
81 {
82 DeleteFileW( db->deletefile );
83 msi_free( db->deletefile );
84 }
85 }
86
87 static HRESULT db_initialize( IStorage *stg, const GUID *clsid )
88 {
89 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
90 HRESULT hr;
91
92 hr = IStorage_SetClass( stg, clsid );
93 if (FAILED( hr ))
94 {
95 WARN("failed to set class id 0x%08x\n", hr);
96 return hr;
97 }
98
99 /* create the _Tables stream */
100 hr = write_stream_data( stg, szTables, NULL, 0, TRUE );
101 if (FAILED( hr ))
102 {
103 WARN("failed to create _Tables stream 0x%08x\n", hr);
104 return hr;
105 }
106
107 hr = msi_init_string_table( stg );
108 if (FAILED( hr ))
109 {
110 WARN("failed to initialize string table 0x%08x\n", hr);
111 return hr;
112 }
113
114 hr = IStorage_Commit( stg, 0 );
115 if (FAILED( hr ))
116 {
117 WARN("failed to commit changes 0x%08x\n", hr);
118 return hr;
119 }
120
121 return S_OK;
122 }
123
124 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
125 {
126 IStorage *stg = NULL;
127 HRESULT r;
128 MSIDATABASE *db = NULL;
129 UINT ret = ERROR_FUNCTION_FAILED;
130 LPCWSTR szMode, save_path;
131 STATSTG stat;
132 BOOL created = FALSE, patch = FALSE;
133 WCHAR path[MAX_PATH];
134
135 TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
136
137 if( !pdb )
138 return ERROR_INVALID_PARAMETER;
139
140 if (szPersist - MSIDBOPEN_PATCHFILE >= MSIDBOPEN_READONLY &&
141 szPersist - MSIDBOPEN_PATCHFILE <= MSIDBOPEN_CREATEDIRECT)
142 {
143 TRACE("Database is a patch\n");
144 szPersist -= MSIDBOPEN_PATCHFILE;
145 patch = TRUE;
146 }
147
148 save_path = szDBPath;
149 szMode = szPersist;
150 if( !IS_INTMSIDBOPEN(szPersist) )
151 {
152 if (!CopyFileW( szDBPath, szPersist, FALSE ))
153 return ERROR_OPEN_FAILED;
154
155 szDBPath = szPersist;
156 szPersist = MSIDBOPEN_TRANSACT;
157 created = TRUE;
158 }
159
160 if( szPersist == MSIDBOPEN_READONLY )
161 {
162 r = StgOpenStorage( szDBPath, NULL,
163 STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
164 }
165 else if( szPersist == MSIDBOPEN_CREATE )
166 {
167 r = StgCreateDocfile( szDBPath,
168 STGM_CREATE|STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
169
170 if( SUCCEEDED(r) )
171 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
172 created = TRUE;
173 }
174 else if( szPersist == MSIDBOPEN_CREATEDIRECT )
175 {
176 r = StgCreateDocfile( szDBPath,
177 STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
178
179 if( SUCCEEDED(r) )
180 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
181 created = TRUE;
182 }
183 else if( szPersist == MSIDBOPEN_TRANSACT )
184 {
185 r = StgOpenStorage( szDBPath, NULL,
186 STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
187 }
188 else if( szPersist == MSIDBOPEN_DIRECT )
189 {
190 r = StgOpenStorage( szDBPath, NULL,
191 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
192 }
193 else
194 {
195 ERR("unknown flag %p\n",szPersist);
196 return ERROR_INVALID_PARAMETER;
197 }
198
199 if( FAILED( r ) || !stg )
200 {
201 WARN("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
202 return ERROR_FUNCTION_FAILED;
203 }
204
205 r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
206 if( FAILED( r ) )
207 {
208 FIXME("Failed to stat storage\n");
209 goto end;
210 }
211
212 if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
213 !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) &&
214 !IsEqualGUID( &stat.clsid, &CLSID_MsiTransform ) )
215 {
216 ERR("storage GUID is not a MSI database GUID %s\n",
217 debugstr_guid(&stat.clsid) );
218 goto end;
219 }
220
221 if ( patch && !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) )
222 {
223 ERR("storage GUID is not the MSI patch GUID %s\n",
224 debugstr_guid(&stat.clsid) );
225 ret = ERROR_OPEN_FAILED;
226 goto end;
227 }
228
229 db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
230 MSI_CloseDatabase );
231 if( !db )
232 {
233 FIXME("Failed to allocate a handle\n");
234 goto end;
235 }
236
237 if (!strchrW( save_path, '\\' ))
238 {
239 GetCurrentDirectoryW( MAX_PATH, path );
240 lstrcatW( path, szBackSlash );
241 lstrcatW( path, save_path );
242 }
243 else
244 lstrcpyW( path, save_path );
245
246 db->path = strdupW( path );
247 db->media_transform_offset = MSI_INITIAL_MEDIA_TRANSFORM_OFFSET;
248 db->media_transform_disk_id = MSI_INITIAL_MEDIA_TRANSFORM_DISKID;
249
250 if( TRACE_ON( msi ) )
251 enum_stream_names( stg );
252
253 db->storage = stg;
254 db->mode = szMode;
255 if (created)
256 db->deletefile = strdupW( szDBPath );
257 list_init( &db->tables );
258 list_init( &db->transforms );
259
260 db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
261 if( !db->strings )
262 goto end;
263
264 ret = ERROR_SUCCESS;
265
266 msiobj_addref( &db->hdr );
267 IStorage_AddRef( stg );
268 *pdb = db;
269
270 end:
271 if( db )
272 msiobj_release( &db->hdr );
273 if( stg )
274 IStorage_Release( stg );
275
276 return ret;
277 }
278
279 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
280 {
281 MSIDATABASE *db;
282 UINT ret;
283
284 TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
285
286 ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
287 if( ret == ERROR_SUCCESS )
288 {
289 *phDB = alloc_msihandle( &db->hdr );
290 if (! *phDB)
291 ret = ERROR_NOT_ENOUGH_MEMORY;
292 msiobj_release( &db->hdr );
293 }
294
295 return ret;
296 }
297
298 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
299 {
300 HRESULT r = ERROR_FUNCTION_FAILED;
301 LPWSTR szwDBPath = NULL, szwPersist = NULL;
302
303 TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
304
305 if( szDBPath )
306 {
307 szwDBPath = strdupAtoW( szDBPath );
308 if( !szwDBPath )
309 goto end;
310 }
311
312 if( !IS_INTMSIDBOPEN(szPersist) )
313 {
314 szwPersist = strdupAtoW( szPersist );
315 if( !szwPersist )
316 goto end;
317 }
318 else
319 szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
320
321 r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
322
323 end:
324 if( !IS_INTMSIDBOPEN(szPersist) )
325 msi_free( szwPersist );
326 msi_free( szwDBPath );
327
328 return r;
329 }
330
331 static LPWSTR msi_read_text_archive(LPCWSTR path, DWORD *len)
332 {
333 HANDLE file;
334 LPSTR data = NULL;
335 LPWSTR wdata = NULL;
336 DWORD read, size = 0;
337
338 file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
339 if (file == INVALID_HANDLE_VALUE)
340 return NULL;
341
342 size = GetFileSize( file, NULL );
343 if (!(data = msi_alloc( size ))) goto done;
344
345 if (!ReadFile( file, data, size, &read, NULL ) || read != size) goto done;
346
347 while (!data[size - 1]) size--;
348 *len = MultiByteToWideChar( CP_ACP, 0, data, size, NULL, 0 );
349 if ((wdata = msi_alloc( (*len + 1) * sizeof(WCHAR) )))
350 {
351 MultiByteToWideChar( CP_ACP, 0, data, size, wdata, *len );
352 wdata[*len] = 0;
353 }
354
355 done:
356 CloseHandle( file );
357 msi_free( data );
358 return wdata;
359 }
360
361 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries, DWORD *len)
362 {
363 LPWSTR ptr = *line, save;
364 DWORD i, count = 1, chars_left = *len;
365
366 *entries = NULL;
367
368 /* stay on this line */
369 while (chars_left && *ptr != '\n')
370 {
371 /* entries are separated by tabs */
372 if (*ptr == '\t')
373 count++;
374
375 ptr++;
376 chars_left--;
377 }
378
379 *entries = msi_alloc(count * sizeof(LPWSTR));
380 if (!*entries)
381 return;
382
383 /* store pointers into the data */
384 chars_left = *len;
385 for (i = 0, ptr = *line; i < count; i++)
386 {
387 while (chars_left && *ptr == '\r')
388 {
389 ptr++;
390 chars_left--;
391 }
392 save = ptr;
393
394 while (chars_left && *ptr != '\t' && *ptr != '\n' && *ptr != '\r')
395 {
396 if (!*ptr) *ptr = '\n'; /* convert embedded nulls to \n */
397 if (ptr > *line && *ptr == '\x19' && *(ptr - 1) == '\x11')
398 {
399 *ptr = '\n';
400 *(ptr - 1) = '\r';
401 }
402 ptr++;
403 chars_left--;
404 }
405
406 /* NULL-separate the data */
407 if (*ptr == '\n' || *ptr == '\r')
408 {
409 while (chars_left && (*ptr == '\n' || *ptr == '\r'))
410 {
411 *(ptr++) = 0;
412 chars_left--;
413 }
414 }
415 else if (*ptr)
416 {
417 *(ptr++) = 0;
418 chars_left--;
419 }
420 (*entries)[i] = save;
421 }
422
423 /* move to the next line if there's more, else EOF */
424 *line = ptr;
425 *len = chars_left;
426 if (num_entries)
427 *num_entries = count;
428 }
429
430 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
431 {
432 LPWSTR prelude;
433 DWORD size;
434
435 static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
436
437 size = sizeof(create_fmt)/sizeof(create_fmt[0]) + lstrlenW(table) - 2;
438 prelude = msi_alloc(size * sizeof(WCHAR));
439 if (!prelude)
440 return NULL;
441
442 sprintfW(prelude, create_fmt, table);
443 return prelude;
444 }
445
446 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
447 {
448 LPWSTR columns, p;
449 LPCWSTR type;
450 DWORD sql_size = 1, i, len;
451 WCHAR expanded[128], *ptr;
452 WCHAR size[10], comma[2], extra[30];
453
454 static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
455 static const WCHAR size_fmt[] = {'(','%','s',')',0};
456 static const WCHAR type_char[] = {'C','H','A','R',0};
457 static const WCHAR type_int[] = {'I','N','T',0};
458 static const WCHAR type_long[] = {'L','O','N','G',0};
459 static const WCHAR type_object[] = {'O','B','J','E','C','T',0};
460 static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
461 static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
462
463 columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
464 if (!columns)
465 return NULL;
466
467 for (i = 0; i < num_columns; i++)
468 {
469 type = NULL;
470 comma[1] = size[0] = extra[0] = '\0';
471
472 if (i == num_columns - 1)
473 comma[0] = '\0';
474 else
475 comma[0] = ',';
476
477 ptr = &types[i][1];
478 len = atolW(ptr);
479 extra[0] = '\0';
480
481 switch (types[i][0])
482 {
483 case 'l':
484 lstrcpyW(extra, type_notnull);
485 /* fall through */
486 case 'L':
487 lstrcatW(extra, localizable);
488 type = type_char;
489 sprintfW(size, size_fmt, ptr);
490 break;
491 case 's':
492 lstrcpyW(extra, type_notnull);
493 /* fall through */
494 case 'S':
495 type = type_char;
496 sprintfW(size, size_fmt, ptr);
497 break;
498 case 'i':
499 lstrcpyW(extra, type_notnull);
500 /* fall through */
501 case 'I':
502 if (len <= 2)
503 type = type_int;
504 else if (len == 4)
505 type = type_long;
506 else
507 {
508 WARN("invalid int width %u\n", len);
509 msi_free(columns);
510 return NULL;
511 }
512 break;
513 case 'v':
514 lstrcpyW(extra, type_notnull);
515 /* fall through */
516 case 'V':
517 type = type_object;
518 break;
519 default:
520 ERR("Unknown type: %c\n", types[i][0]);
521 msi_free(columns);
522 return NULL;
523 }
524
525 sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
526 sql_size += lstrlenW(expanded);
527
528 p = msi_realloc(columns, sql_size * sizeof(WCHAR));
529 if (!p)
530 {
531 msi_free(columns);
532 return NULL;
533 }
534 columns = p;
535
536 lstrcatW(columns, expanded);
537 }
538
539 return columns;
540 }
541
542 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
543 {
544 LPWSTR postlude, keys, ptr;
545 DWORD size, key_size, i;
546
547 static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
548 static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
549
550 for (i = 0, size = 1; i < num_keys; i++)
551 size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
552
553 keys = msi_alloc(size * sizeof(WCHAR));
554 if (!keys)
555 return NULL;
556
557 for (i = 0, ptr = keys; i < num_keys; i++)
558 {
559 key_size = lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) -2;
560 sprintfW(ptr, key_fmt, primary_keys[i]);
561 ptr += key_size;
562 }
563
564 /* remove final ', ' */
565 *(ptr - 2) = '\0';
566
567 size = lstrlenW(postlude_fmt) + size - 1;
568 postlude = msi_alloc(size * sizeof(WCHAR));
569 if (!postlude)
570 goto done;
571
572 sprintfW(postlude, postlude_fmt, keys);
573
574 done:
575 msi_free(keys);
576 return postlude;
577 }
578
579 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
580 {
581 UINT r = ERROR_OUTOFMEMORY;
582 DWORD size;
583 MSIQUERY *view;
584 LPWSTR create_sql = NULL;
585 LPWSTR prelude, columns_sql, postlude;
586
587 prelude = msi_build_createsql_prelude(labels[0]);
588 columns_sql = msi_build_createsql_columns(columns, types, num_columns);
589 postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
590
591 if (!prelude || !columns_sql || !postlude)
592 goto done;
593
594 size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
595 create_sql = msi_alloc(size * sizeof(WCHAR));
596 if (!create_sql)
597 goto done;
598
599 lstrcpyW(create_sql, prelude);
600 lstrcatW(create_sql, columns_sql);
601 lstrcatW(create_sql, postlude);
602
603 r = MSI_DatabaseOpenViewW( db, create_sql, &view );
604 if (r != ERROR_SUCCESS)
605 goto done;
606
607 r = MSI_ViewExecute(view, NULL);
608 MSI_ViewClose(view);
609 msiobj_release(&view->hdr);
610
611 done:
612 msi_free(prelude);
613 msi_free(columns_sql);
614 msi_free(postlude);
615 msi_free(create_sql);
616 return r;
617 }
618
619 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
620 {
621 DWORD len;
622 LPWSTR fullname, ptr;
623
624 len = lstrlenW(path) + lstrlenW(name) + 1;
625 fullname = msi_alloc(len*sizeof(WCHAR));
626 if (!fullname)
627 return NULL;
628
629 lstrcpyW( fullname, path );
630
631 /* chop off extension from path */
632 ptr = strrchrW(fullname, '.');
633 if (!ptr)
634 {
635 msi_free (fullname);
636 return NULL;
637 }
638 *ptr++ = '\\';
639 lstrcpyW( ptr, name );
640 return fullname;
641 }
642
643 static UINT construct_record(DWORD num_columns, LPWSTR *types,
644 LPWSTR *data, LPWSTR path, MSIRECORD **rec)
645 {
646 UINT i;
647
648 *rec = MSI_CreateRecord(num_columns);
649 if (!*rec)
650 return ERROR_OUTOFMEMORY;
651
652 for (i = 0; i < num_columns; i++)
653 {
654 switch (types[i][0])
655 {
656 case 'L': case 'l': case 'S': case 's':
657 MSI_RecordSetStringW(*rec, i + 1, data[i]);
658 break;
659 case 'I': case 'i':
660 if (*data[i])
661 MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
662 break;
663 case 'V': case 'v':
664 if (*data[i])
665 {
666 UINT r;
667 LPWSTR file = msi_import_stream_filename(path, data[i]);
668 if (!file)
669 return ERROR_FUNCTION_FAILED;
670
671 r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
672 msi_free (file);
673 if (r != ERROR_SUCCESS)
674 return ERROR_FUNCTION_FAILED;
675 }
676 break;
677 default:
678 ERR("Unhandled column type: %c\n", types[i][0]);
679 msiobj_release(&(*rec)->hdr);
680 return ERROR_FUNCTION_FAILED;
681 }
682 }
683
684 return ERROR_SUCCESS;
685 }
686
687 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
688 LPWSTR *labels, LPWSTR **records,
689 int num_columns, int num_records,
690 LPWSTR path)
691 {
692 UINT r;
693 int i;
694 MSIQUERY *view;
695 MSIRECORD *rec;
696
697 static const WCHAR select[] = {
698 'S','E','L','E','C','T',' ','*',' ',
699 'F','R','O','M',' ','`','%','s','`',0
700 };
701
702 r = MSI_OpenQuery(db, &view, select, labels[0]);
703 if (r != ERROR_SUCCESS)
704 return r;
705
706 while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
707 {
708 r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
709 msiobj_release(&rec->hdr);
710 if (r != ERROR_SUCCESS)
711 goto done;
712 }
713
714 for (i = 0; i < num_records; i++)
715 {
716 r = construct_record(num_columns, types, records[i], path, &rec);
717 if (r != ERROR_SUCCESS)
718 goto done;
719
720 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
721 if (r != ERROR_SUCCESS)
722 {
723 msiobj_release(&rec->hdr);
724 goto done;
725 }
726
727 msiobj_release(&rec->hdr);
728 }
729
730 done:
731 msiobj_release(&view->hdr);
732 return r;
733 }
734
735 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
736 {
737 UINT r;
738 DWORD len, i;
739 DWORD num_labels, num_types;
740 DWORD num_columns, num_records = 0;
741 LPWSTR *columns, *types, *labels;
742 LPWSTR path, ptr, data;
743 LPWSTR **records = NULL;
744 LPWSTR **temp_records;
745
746 static const WCHAR suminfo[] =
747 {'_','S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0};
748 static const WCHAR forcecodepage[] =
749 {'_','F','o','r','c','e','C','o','d','e','p','a','g','e',0};
750
751 TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
752
753 if( folder == NULL || file == NULL )
754 return ERROR_INVALID_PARAMETER;
755
756 len = lstrlenW(folder) + lstrlenW(szBackSlash) + lstrlenW(file) + 1;
757 path = msi_alloc( len * sizeof(WCHAR) );
758 if (!path)
759 return ERROR_OUTOFMEMORY;
760
761 lstrcpyW( path, folder );
762 lstrcatW( path, szBackSlash );
763 lstrcatW( path, file );
764
765 data = msi_read_text_archive( path, &len );
766
767 ptr = data;
768 msi_parse_line( &ptr, &columns, &num_columns, &len );
769 msi_parse_line( &ptr, &types, &num_types, &len );
770 msi_parse_line( &ptr, &labels, &num_labels, &len );
771
772 if (num_columns == 1 && !columns[0][0] && num_labels == 1 && !labels[0][0] &&
773 num_types == 2 && !strcmpW( types[1], forcecodepage ))
774 {
775 r = msi_set_string_table_codepage( db->strings, atoiW( types[0] ) );
776 goto done;
777 }
778
779 if (num_columns != num_types)
780 {
781 r = ERROR_FUNCTION_FAILED;
782 goto done;
783 }
784
785 records = msi_alloc(sizeof(LPWSTR *));
786 if (!records)
787 {
788 r = ERROR_OUTOFMEMORY;
789 goto done;
790 }
791
792 /* read in the table records */
793 while (len)
794 {
795 msi_parse_line( &ptr, &records[num_records], NULL, &len );
796
797 num_records++;
798 temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
799 if (!temp_records)
800 {
801 r = ERROR_OUTOFMEMORY;
802 goto done;
803 }
804 records = temp_records;
805 }
806
807 if (!strcmpW(labels[0], suminfo))
808 {
809 r = msi_add_suminfo( db, records, num_records, num_columns );
810 if (r != ERROR_SUCCESS)
811 {
812 r = ERROR_FUNCTION_FAILED;
813 goto done;
814 }
815 }
816 else
817 {
818 if (!TABLE_Exists(db, labels[0]))
819 {
820 r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
821 if (r != ERROR_SUCCESS)
822 {
823 r = ERROR_FUNCTION_FAILED;
824 goto done;
825 }
826 }
827
828 r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
829 }
830
831 done:
832 msi_free(path);
833 msi_free(data);
834 msi_free(columns);
835 msi_free(types);
836 msi_free(labels);
837
838 for (i = 0; i < num_records; i++)
839 msi_free(records[i]);
840
841 msi_free(records);
842
843 return r;
844 }
845
846 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
847 {
848 MSIDATABASE *db;
849 UINT r;
850
851 TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
852
853 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
854 if( !db )
855 {
856 IWineMsiRemoteDatabase *remote_database;
857
858 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
859 if ( !remote_database )
860 return ERROR_INVALID_HANDLE;
861
862 IWineMsiRemoteDatabase_Release( remote_database );
863 WARN("MsiDatabaseImport not allowed during a custom action!\n");
864
865 return ERROR_SUCCESS;
866 }
867
868 r = MSI_DatabaseImport( db, szFolder, szFilename );
869 msiobj_release( &db->hdr );
870 return r;
871 }
872
873 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
874 LPCSTR szFolder, LPCSTR szFilename )
875 {
876 LPWSTR path = NULL, file = NULL;
877 UINT r = ERROR_OUTOFMEMORY;
878
879 TRACE("%x %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
880
881 if( szFolder )
882 {
883 path = strdupAtoW( szFolder );
884 if( !path )
885 goto end;
886 }
887
888 if( szFilename )
889 {
890 file = strdupAtoW( szFilename );
891 if( !file )
892 goto end;
893 }
894
895 r = MsiDatabaseImportW( handle, path, file );
896
897 end:
898 msi_free( path );
899 msi_free( file );
900
901 return r;
902 }
903
904 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
905 {
906 UINT i, count, len, r = ERROR_SUCCESS;
907 const char *sep;
908 char *buffer;
909 DWORD sz;
910
911 len = 0x100;
912 buffer = msi_alloc( len );
913 if ( !buffer )
914 return ERROR_OUTOFMEMORY;
915
916 count = MSI_RecordGetFieldCount( row );
917 for ( i=start; i<=count; i++ )
918 {
919 sz = len;
920 r = MSI_RecordGetStringA( row, i, buffer, &sz );
921 if (r == ERROR_MORE_DATA)
922 {
923 char *p = msi_realloc( buffer, sz + 1 );
924 if (!p)
925 break;
926 len = sz + 1;
927 buffer = p;
928 }
929 sz = len;
930 r = MSI_RecordGetStringA( row, i, buffer, &sz );
931 if (r != ERROR_SUCCESS)
932 break;
933
934 if (!WriteFile( handle, buffer, sz, &sz, NULL ))
935 {
936 r = ERROR_FUNCTION_FAILED;
937 break;
938 }
939
940 sep = (i < count) ? "\t" : "\r\n";
941 if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
942 {
943 r = ERROR_FUNCTION_FAILED;
944 break;
945 }
946 }
947 msi_free( buffer );
948 return r;
949 }
950
951 static UINT msi_export_row( MSIRECORD *row, void *arg )
952 {
953 return msi_export_record( arg, row, 1 );
954 }
955
956 static UINT msi_export_forcecodepage( HANDLE handle, UINT codepage )
957 {
958 static const char fmt[] = "\r\n\r\n%u\t_ForceCodepage\r\n";
959 char data[sizeof(fmt) + 10];
960 DWORD sz;
961
962 sprintf( data, fmt, codepage );
963
964 sz = lstrlenA(data) + 1;
965 if (!WriteFile(handle, data, sz, &sz, NULL))
966 return ERROR_FUNCTION_FAILED;
967
968 return ERROR_SUCCESS;
969 }
970
971 static UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
972 LPCWSTR folder, LPCWSTR file )
973 {
974 static const WCHAR query[] = {
975 's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
976 static const WCHAR forcecodepage[] = {
977 '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
978 MSIRECORD *rec = NULL;
979 MSIQUERY *view = NULL;
980 LPWSTR filename;
981 HANDLE handle;
982 UINT len, r;
983
984 TRACE("%p %s %s %s\n", db, debugstr_w(table),
985 debugstr_w(folder), debugstr_w(file) );
986
987 if( folder == NULL || file == NULL )
988 return ERROR_INVALID_PARAMETER;
989
990 len = lstrlenW(folder) + lstrlenW(file) + 2;
991 filename = msi_alloc(len * sizeof (WCHAR));
992 if (!filename)
993 return ERROR_OUTOFMEMORY;
994
995 lstrcpyW( filename, folder );
996 lstrcatW( filename, szBackSlash );
997 lstrcatW( filename, file );
998
999 handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
1000 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
1001 msi_free( filename );
1002 if (handle == INVALID_HANDLE_VALUE)
1003 return ERROR_FUNCTION_FAILED;
1004
1005 if (!strcmpW( table, forcecodepage ))
1006 {
1007 UINT codepage = msi_get_string_table_codepage( db->strings );
1008 r = msi_export_forcecodepage( handle, codepage );
1009 goto done;
1010 }
1011
1012 r = MSI_OpenQuery( db, &view, query, table );
1013 if (r == ERROR_SUCCESS)
1014 {
1015 /* write out row 1, the column names */
1016 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
1017 if (r == ERROR_SUCCESS)
1018 {
1019 msi_export_record( handle, rec, 1 );
1020 msiobj_release( &rec->hdr );
1021 }
1022
1023 /* write out row 2, the column types */
1024 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
1025 if (r == ERROR_SUCCESS)
1026 {
1027 msi_export_record( handle, rec, 1 );
1028 msiobj_release( &rec->hdr );
1029 }
1030
1031 /* write out row 3, the table name + keys */
1032 r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
1033 if (r == ERROR_SUCCESS)
1034 {
1035 MSI_RecordSetStringW( rec, 0, table );
1036 msi_export_record( handle, rec, 0 );
1037 msiobj_release( &rec->hdr );
1038 }
1039
1040 /* write out row 4 onwards, the data */
1041 r = MSI_IterateRecords( view, 0, msi_export_row, handle );
1042 msiobj_release( &view->hdr );
1043 }
1044
1045 done:
1046 CloseHandle( handle );
1047 return r;
1048 }
1049
1050 /***********************************************************************
1051 * MsiExportDatabaseW [MSI.@]
1052 *
1053 * Writes a file containing the table data as tab separated ASCII.
1054 *
1055 * The format is as follows:
1056 *
1057 * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
1058 * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
1059 * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
1060 *
1061 * Followed by the data, starting at row 1 with one row per line
1062 *
1063 * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
1064 */
1065 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
1066 LPCWSTR szFolder, LPCWSTR szFilename )
1067 {
1068 MSIDATABASE *db;
1069 UINT r;
1070
1071 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
1072 debugstr_w(szFolder), debugstr_w(szFilename));
1073
1074 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1075 if( !db )
1076 {
1077 IWineMsiRemoteDatabase *remote_database;
1078
1079 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1080 if ( !remote_database )
1081 return ERROR_INVALID_HANDLE;
1082
1083 IWineMsiRemoteDatabase_Release( remote_database );
1084 WARN("MsiDatabaseExport not allowed during a custom action!\n");
1085
1086 return ERROR_SUCCESS;
1087 }
1088
1089 r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
1090 msiobj_release( &db->hdr );
1091 return r;
1092 }
1093
1094 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
1095 LPCSTR szFolder, LPCSTR szFilename )
1096 {
1097 LPWSTR path = NULL, file = NULL, table = NULL;
1098 UINT r = ERROR_OUTOFMEMORY;
1099
1100 TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1101 debugstr_a(szFolder), debugstr_a(szFilename));
1102
1103 if( szTable )
1104 {
1105 table = strdupAtoW( szTable );
1106 if( !table )
1107 goto end;
1108 }
1109
1110 if( szFolder )
1111 {
1112 path = strdupAtoW( szFolder );
1113 if( !path )
1114 goto end;
1115 }
1116
1117 if( szFilename )
1118 {
1119 file = strdupAtoW( szFilename );
1120 if( !file )
1121 goto end;
1122 }
1123
1124 r = MsiDatabaseExportW( handle, table, path, file );
1125
1126 end:
1127 msi_free( table );
1128 msi_free( path );
1129 msi_free( file );
1130
1131 return r;
1132 }
1133
1134 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1135 LPCSTR szTableName)
1136 {
1137 UINT r;
1138 LPWSTR table;
1139
1140 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1141 debugstr_a(szTableName));
1142
1143 table = strdupAtoW(szTableName);
1144 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1145
1146 msi_free(table);
1147 return r;
1148 }
1149
1150 typedef struct _tagMERGETABLE
1151 {
1152 struct list entry;
1153 struct list rows;
1154 LPWSTR name;
1155 DWORD numconflicts;
1156 LPWSTR *columns;
1157 DWORD numcolumns;
1158 LPWSTR *types;
1159 DWORD numtypes;
1160 LPWSTR *labels;
1161 DWORD numlabels;
1162 } MERGETABLE;
1163
1164 typedef struct _tagMERGEROW
1165 {
1166 struct list entry;
1167 MSIRECORD *data;
1168 } MERGEROW;
1169
1170 typedef struct _tagMERGEDATA
1171 {
1172 MSIDATABASE *db;
1173 MSIDATABASE *merge;
1174 MERGETABLE *curtable;
1175 MSIQUERY *curview;
1176 struct list *tabledata;
1177 } MERGEDATA;
1178
1179 static BOOL merge_type_match(LPCWSTR type1, LPCWSTR type2)
1180 {
1181 if (((type1[0] == 'l') || (type1[0] == 's')) &&
1182 ((type2[0] == 'l') || (type2[0] == 's')))
1183 return TRUE;
1184
1185 if (((type1[0] == 'L') || (type1[0] == 'S')) &&
1186 ((type2[0] == 'L') || (type2[0] == 'S')))
1187 return TRUE;
1188
1189 return !strcmpW( type1, type2 );
1190 }
1191
1192 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1193 {
1194 MSIRECORD *dbrec, *mergerec;
1195 UINT r, i, count;
1196
1197 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1198 if (r != ERROR_SUCCESS)
1199 return r;
1200
1201 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1202 if (r != ERROR_SUCCESS)
1203 {
1204 msiobj_release(&dbrec->hdr);
1205 return r;
1206 }
1207
1208 count = MSI_RecordGetFieldCount(dbrec);
1209 for (i = 1; i <= count; i++)
1210 {
1211 if (!MSI_RecordGetString(mergerec, i))
1212 break;
1213
1214 if (strcmpW( MSI_RecordGetString( dbrec, i ), MSI_RecordGetString( mergerec, i ) ))
1215 {
1216 r = ERROR_DATATYPE_MISMATCH;
1217 goto done;
1218 }
1219 }
1220
1221 msiobj_release(&dbrec->hdr);
1222 msiobj_release(&mergerec->hdr);
1223 dbrec = mergerec = NULL;
1224
1225 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1226 if (r != ERROR_SUCCESS)
1227 return r;
1228
1229 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1230 if (r != ERROR_SUCCESS)
1231 {
1232 msiobj_release(&dbrec->hdr);
1233 return r;
1234 }
1235
1236 count = MSI_RecordGetFieldCount(dbrec);
1237 for (i = 1; i <= count; i++)
1238 {
1239 if (!MSI_RecordGetString(mergerec, i))
1240 break;
1241
1242 if (!merge_type_match(MSI_RecordGetString(dbrec, i),
1243 MSI_RecordGetString(mergerec, i)))
1244 {
1245 r = ERROR_DATATYPE_MISMATCH;
1246 break;
1247 }
1248 }
1249
1250 done:
1251 msiobj_release(&dbrec->hdr);
1252 msiobj_release(&mergerec->hdr);
1253
1254 return r;
1255 }
1256
1257 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1258 LPCWSTR table)
1259 {
1260 MSIRECORD *dbrec, *mergerec = NULL;
1261 UINT r, i, count;
1262
1263 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1264 if (r != ERROR_SUCCESS)
1265 return r;
1266
1267 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1268 if (r != ERROR_SUCCESS)
1269 goto done;
1270
1271 count = MSI_RecordGetFieldCount(dbrec);
1272 if (count != MSI_RecordGetFieldCount(mergerec))
1273 {
1274 r = ERROR_DATATYPE_MISMATCH;
1275 goto done;
1276 }
1277
1278 for (i = 1; i <= count; i++)
1279 {
1280 if (strcmpW( MSI_RecordGetString( dbrec, i ), MSI_RecordGetString( mergerec, i ) ))
1281 {
1282 r = ERROR_DATATYPE_MISMATCH;
1283 goto done;
1284 }
1285 }
1286
1287 done:
1288 msiobj_release(&dbrec->hdr);
1289 msiobj_release(&mergerec->hdr);
1290
1291 return r;
1292 }
1293
1294 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1295 {
1296 MSIRECORD *colnames;
1297 LPWSTR str, val;
1298 UINT r, i = 0, sz = 0;
1299 int cmp;
1300
1301 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1302 if (r != ERROR_SUCCESS)
1303 return NULL;
1304
1305 do
1306 {
1307 str = msi_dup_record_field(colnames, ++i);
1308 cmp = strcmpW( key, str );
1309 msi_free(str);
1310 } while (cmp);
1311
1312 msiobj_release(&colnames->hdr);
1313
1314 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1315 if (r != ERROR_SUCCESS)
1316 return NULL;
1317 sz++;
1318
1319 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1320 {
1321 /* quote string record fields */
1322 const WCHAR szQuote[] = {'\'', 0};
1323 sz += 2;
1324 val = msi_alloc(sz*sizeof(WCHAR));
1325 if (!val)
1326 return NULL;
1327
1328 lstrcpyW(val, szQuote);
1329 r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1330 lstrcpyW(val+1+sz, szQuote);
1331 }
1332 else
1333 {
1334 /* do not quote integer record fields */
1335 val = msi_alloc(sz*sizeof(WCHAR));
1336 if (!val)
1337 return NULL;
1338
1339 r = MSI_RecordGetStringW(rec, i, val, &sz);
1340 }
1341
1342 if (r != ERROR_SUCCESS)
1343 {
1344 ERR("failed to get string!\n");
1345 msi_free(val);
1346 return NULL;
1347 }
1348
1349 return val;
1350 }
1351
1352 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1353 LPWSTR table, MSIRECORD *rec)
1354 {
1355 LPWSTR query = NULL, clause = NULL, val;
1356 LPCWSTR setptr, key;
1357 DWORD size, oldsize;
1358 MSIRECORD *keys;
1359 UINT r, i, count;
1360
1361 static const WCHAR keyset[] = {
1362 '`','%','s','`',' ','=',' ','%','s',' ','A','N','D',' ',0};
1363 static const WCHAR lastkeyset[] = {
1364 '`','%','s','`',' ','=',' ','%','s',' ',0};
1365 static const WCHAR fmt[] = {'S','E','L','E','C','T',' ','*',' ',
1366 'F','R','O','M',' ','`','%','s','`',' ',
1367 'W','H','E','R','E',' ','%','s',0};
1368
1369 r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1370 if (r != ERROR_SUCCESS)
1371 return NULL;
1372
1373 clause = msi_alloc_zero(sizeof(WCHAR));
1374 if (!clause)
1375 goto done;
1376
1377 size = 1;
1378 count = MSI_RecordGetFieldCount(keys);
1379 for (i = 1; i <= count; i++)
1380 {
1381 key = MSI_RecordGetString(keys, i);
1382 val = get_key_value(view, key, rec);
1383
1384 if (i == count)
1385 setptr = lastkeyset;
1386 else
1387 setptr = keyset;
1388
1389 oldsize = size;
1390 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1391 clause = msi_realloc(clause, size * sizeof (WCHAR));
1392 if (!clause)
1393 {
1394 msi_free(val);
1395 goto done;
1396 }
1397
1398 sprintfW(clause + oldsize - 1, setptr, key, val);
1399 msi_free(val);
1400 }
1401
1402 size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1403 query = msi_alloc(size * sizeof(WCHAR));
1404 if (!query)
1405 goto done;
1406
1407 sprintfW(query, fmt, table, clause);
1408
1409 done:
1410 msi_free(clause);
1411 msiobj_release(&keys->hdr);
1412 return query;
1413 }
1414
1415 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1416 {
1417 MERGEDATA *data = param;
1418 MERGETABLE *table = data->curtable;
1419 MERGEROW *mergerow;
1420 MSIQUERY *dbview = NULL;
1421 MSIRECORD *row = NULL;
1422 LPWSTR query = NULL;
1423 UINT r = ERROR_SUCCESS;
1424
1425 if (TABLE_Exists(data->db, table->name))
1426 {
1427 query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1428 if (!query)
1429 return ERROR_OUTOFMEMORY;
1430
1431 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1432 if (r != ERROR_SUCCESS)
1433 goto done;
1434
1435 r = MSI_ViewExecute(dbview, NULL);
1436 if (r != ERROR_SUCCESS)
1437 goto done;
1438
1439 r = MSI_ViewFetch(dbview, &row);
1440 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1441 {
1442 table->numconflicts++;
1443 goto done;
1444 }
1445 else if (r != ERROR_NO_MORE_ITEMS)
1446 goto done;
1447
1448 r = ERROR_SUCCESS;
1449 }
1450
1451 mergerow = msi_alloc(sizeof(MERGEROW));
1452 if (!mergerow)
1453 {
1454 r = ERROR_OUTOFMEMORY;
1455 goto done;
1456 }
1457
1458 mergerow->data = MSI_CloneRecord(rec);
1459 if (!mergerow->data)
1460 {
1461 r = ERROR_OUTOFMEMORY;
1462 msi_free(mergerow);
1463 goto done;
1464 }
1465
1466 list_add_tail(&table->rows, &mergerow->entry);
1467
1468 done:
1469 msi_free(query);
1470 msiobj_release(&row->hdr);
1471 msiobj_release(&dbview->hdr);
1472 return r;
1473 }
1474
1475 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1476 {
1477 UINT r, i, count;
1478 MSIRECORD *prec = NULL;
1479
1480 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1481 if (r != ERROR_SUCCESS)
1482 return r;
1483
1484 count = MSI_RecordGetFieldCount(prec);
1485 *numlabels = count + 1;
1486 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1487 if (!*labels)
1488 {
1489 r = ERROR_OUTOFMEMORY;
1490 goto end;
1491 }
1492
1493 (*labels)[0] = strdupW(table);
1494 for (i=1; i<=count; i++ )
1495 {
1496 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1497 }
1498
1499 end:
1500 msiobj_release( &prec->hdr );
1501 return r;
1502 }
1503
1504 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1505 {
1506 UINT r, i, count;
1507 MSIRECORD *prec = NULL;
1508
1509 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1510 if (r != ERROR_SUCCESS)
1511 return r;
1512
1513 count = MSI_RecordGetFieldCount(prec);
1514 *columns = msi_alloc(count*sizeof(LPWSTR));
1515 if (!*columns)
1516 {
1517 r = ERROR_OUTOFMEMORY;
1518 goto end;
1519 }
1520
1521 for (i=1; i<=count; i++ )
1522 {
1523 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1524 }
1525
1526 *numcolumns = count;
1527
1528 end:
1529 msiobj_release( &prec->hdr );
1530 return r;
1531 }
1532
1533 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1534 {
1535 UINT r, i, count;
1536 MSIRECORD *prec = NULL;
1537
1538 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1539 if (r != ERROR_SUCCESS)
1540 return r;
1541
1542 count = MSI_RecordGetFieldCount(prec);
1543 *types = msi_alloc(count*sizeof(LPWSTR));
1544 if (!*types)
1545 {
1546 r = ERROR_OUTOFMEMORY;
1547 goto end;
1548 }
1549
1550 *numtypes = count;
1551 for (i=1; i<=count; i++ )
1552 {
1553 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1554 }
1555
1556 end:
1557 msiobj_release( &prec->hdr );
1558 return r;
1559 }
1560
1561 static void merge_free_rows(MERGETABLE *table)
1562 {
1563 struct list *item, *cursor;
1564
1565 LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1566 {
1567 MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1568
1569 list_remove(&row->entry);
1570 msiobj_release(&row->data->hdr);
1571 msi_free(row);
1572 }
1573 }
1574
1575 static void free_merge_table(MERGETABLE *table)
1576 {
1577 UINT i;
1578
1579 if (table->labels != NULL)
1580 {
1581 for (i = 0; i < table->numlabels; i++)
1582 msi_free(table->labels[i]);
1583
1584 msi_free(table->labels);
1585 }
1586
1587 if (table->columns != NULL)
1588 {
1589 for (i = 0; i < table->numcolumns; i++)
1590 msi_free(table->columns[i]);
1591
1592 msi_free(table->columns);
1593 }
1594
1595 if (table->types != NULL)
1596 {
1597 for (i = 0; i < table->numtypes; i++)
1598 msi_free(table->types[i]);
1599
1600 msi_free(table->types);
1601 }
1602
1603 msi_free(table->name);
1604 merge_free_rows(table);
1605
1606 msi_free(table);
1607 }
1608
1609 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1610 {
1611 UINT r;
1612 MERGETABLE *table;
1613 MSIQUERY *mergeview = NULL;
1614
1615 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1616 'F','R','O','M',' ','`','%','s','`',0};
1617
1618 table = msi_alloc_zero(sizeof(MERGETABLE));
1619 if (!table)
1620 {
1621 *ptable = NULL;
1622 return ERROR_OUTOFMEMORY;
1623 }
1624
1625 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1626 if (r != ERROR_SUCCESS)
1627 goto err;
1628
1629 r = MSI_OpenQuery(db, &mergeview, query, name);
1630 if (r != ERROR_SUCCESS)
1631 goto err;
1632
1633 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1634 if (r != ERROR_SUCCESS)
1635 goto err;
1636
1637 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1638 if (r != ERROR_SUCCESS)
1639 goto err;
1640
1641 list_init(&table->rows);
1642
1643 table->name = strdupW(name);
1644 table->numconflicts = 0;
1645
1646 msiobj_release(&mergeview->hdr);
1647 *ptable = table;
1648 return ERROR_SUCCESS;
1649
1650 err:
1651 msiobj_release(&mergeview->hdr);
1652 free_merge_table(table);
1653 *ptable = NULL;
1654 return r;
1655 }
1656
1657 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1658 {
1659 MERGEDATA *data = param;
1660 MERGETABLE *table;
1661 MSIQUERY *dbview = NULL;
1662 MSIQUERY *mergeview = NULL;
1663 LPCWSTR name;
1664 UINT r;
1665
1666 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1667 'F','R','O','M',' ','`','%','s','`',0};
1668
1669 name = MSI_RecordGetString(rec, 1);
1670
1671 r = MSI_OpenQuery(data->merge, &mergeview, query, name);
1672 if (r != ERROR_SUCCESS)
1673 goto done;
1674
1675 if (TABLE_Exists(data->db, name))
1676 {
1677 r = MSI_OpenQuery(data->db, &dbview, query, name);
1678 if (r != ERROR_SUCCESS)
1679 goto done;
1680
1681 r = merge_verify_colnames(dbview, mergeview);
1682 if (r != ERROR_SUCCESS)
1683 goto done;
1684
1685 r = merge_verify_primary_keys(data->db, data->merge, name);
1686 if (r != ERROR_SUCCESS)
1687 goto done;
1688 }
1689
1690 r = msi_get_merge_table(data->merge, name, &table);
1691 if (r != ERROR_SUCCESS)
1692 goto done;
1693
1694 data->curtable = table;
1695 data->curview = mergeview;
1696 r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1697 if (r != ERROR_SUCCESS)
1698 {
1699 free_merge_table(table);
1700 goto done;
1701 }
1702
1703 list_add_tail(data->tabledata, &table->entry);
1704
1705 done:
1706 msiobj_release(&dbview->hdr);
1707 msiobj_release(&mergeview->hdr);
1708 return r;
1709 }
1710
1711 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1712 struct list *tabledata)
1713 {
1714 static const WCHAR query[] = {
1715 'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
1716 '`','_','T','a','b','l','e','s','`',0};
1717 MSIQUERY *view;
1718 MERGEDATA data;
1719 UINT r;
1720
1721 r = MSI_DatabaseOpenViewW(merge, query, &view);
1722 if (r != ERROR_SUCCESS)
1723 return r;
1724
1725 data.db = db;
1726 data.merge = merge;
1727 data.tabledata = tabledata;
1728 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1729 msiobj_release(&view->hdr);
1730 return r;
1731 }
1732
1733 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1734 {
1735 UINT r;
1736 MERGEROW *row;
1737 MSIVIEW *tv;
1738
1739 if (!TABLE_Exists(db, table->name))
1740 {
1741 r = msi_add_table_to_db(db, table->columns, table->types,
1742 table->labels, table->numlabels, table->numcolumns);
1743 if (r != ERROR_SUCCESS)
1744 return ERROR_FUNCTION_FAILED;
1745 }
1746
1747 LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1748 {
1749 r = TABLE_CreateView(db, table->name, &tv);
1750 if (r != ERROR_SUCCESS)
1751 return r;
1752
1753 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1754 tv->ops->delete(tv);
1755
1756 if (r != ERROR_SUCCESS)
1757 return r;
1758 }
1759
1760 return ERROR_SUCCESS;
1761 }
1762
1763 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1764 LPWSTR table, DWORD numconflicts)
1765 {
1766 UINT r;
1767 MSIQUERY *view;
1768
1769 static const WCHAR create[] = {
1770 'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
1771 '`','%','s','`',' ','(','`','T','a','b','l','e','`',' ',
1772 'C','H','A','R','(','2','5','5',')',' ','N','O','T',' ',
1773 'N','U','L','L',',',' ','`','N','u','m','R','o','w','M','e','r','g','e',
1774 'C','o','n','f','l','i','c','t','s','`',' ','S','H','O','R','T',' ',
1775 'N','O','T',' ','N','U','L','L',' ','P','R','I','M','A','R','Y',' ',
1776 'K','E','Y',' ','`','T','a','b','l','e','`',')',0};
1777 static const WCHAR insert[] = {
1778 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1779 '`','%','s','`',' ','(','`','T','a','b','l','e','`',',',' ',
1780 '`','N','u','m','R','o','w','M','e','r','g','e',
1781 'C','o','n','f','l','i','c','t','s','`',')',' ','V','A','L','U','E','S',
1782 ' ','(','\'','%','s','\'',',',' ','%','d',')',0};
1783
1784 if (!TABLE_Exists(db, error))
1785 {
1786 r = MSI_OpenQuery(db, &view, create, error);
1787 if (r != ERROR_SUCCESS)
1788 return r;
1789
1790 r = MSI_ViewExecute(view, NULL);
1791 msiobj_release(&view->hdr);
1792 if (r != ERROR_SUCCESS)
1793 return r;
1794 }
1795
1796 r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1797 if (r != ERROR_SUCCESS)
1798 return r;
1799
1800 r = MSI_ViewExecute(view, NULL);
1801 msiobj_release(&view->hdr);
1802 return r;
1803 }
1804
1805 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1806 LPCWSTR szTableName)
1807 {
1808 struct list tabledata = LIST_INIT(tabledata);
1809 struct list *item, *cursor;
1810 MSIDATABASE *db, *merge;
1811 MERGETABLE *table;
1812 BOOL conflicts;
1813 UINT r;
1814
1815 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1816 debugstr_w(szTableName));
1817
1818 if (szTableName && !*szTableName)
1819 return ERROR_INVALID_TABLE;
1820
1821 db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1822 merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1823 if (!db || !merge)
1824 {
1825 r = ERROR_INVALID_HANDLE;
1826 goto done;
1827 }
1828
1829 r = gather_merge_data(db, merge, &tabledata);
1830 if (r != ERROR_SUCCESS)
1831 goto done;
1832
1833 conflicts = FALSE;
1834 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1835 {
1836 if (table->numconflicts)
1837 {
1838 conflicts = TRUE;
1839
1840 r = update_merge_errors(db, szTableName, table->name,
1841 table->numconflicts);
1842 if (r != ERROR_SUCCESS)
1843 break;
1844 }
1845 else
1846 {
1847 r = merge_table(db, table);
1848 if (r != ERROR_SUCCESS)
1849 break;
1850 }
1851 }
1852
1853 LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
1854 {
1855 MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
1856 list_remove(&table->entry);
1857 free_merge_table(table);
1858 }
1859
1860 if (conflicts)
1861 r = ERROR_FUNCTION_FAILED;
1862
1863 done:
1864 msiobj_release(&db->hdr);
1865 msiobj_release(&merge->hdr);
1866 return r;
1867 }
1868
1869 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
1870 {
1871 MSIDBSTATE ret = MSIDBSTATE_READ;
1872 MSIDATABASE *db;
1873
1874 TRACE("%d\n", handle);
1875
1876 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1877 if( !db )
1878 {
1879 IWineMsiRemoteDatabase *remote_database;
1880
1881 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1882 if ( !remote_database )
1883 return MSIDBSTATE_ERROR;
1884
1885 IWineMsiRemoteDatabase_Release( remote_database );
1886 WARN("MsiGetDatabaseState not allowed during a custom action!\n");
1887
1888 return MSIDBSTATE_READ;
1889 }
1890
1891 if (db->mode != MSIDBOPEN_READONLY )
1892 ret = MSIDBSTATE_WRITE;
1893 msiobj_release( &db->hdr );
1894
1895 return ret;
1896 }
1897
1898 typedef struct _msi_remote_database_impl {
1899 IWineMsiRemoteDatabase IWineMsiRemoteDatabase_iface;
1900 MSIHANDLE database;
1901 LONG refs;
1902 } msi_remote_database_impl;
1903
1904 static inline msi_remote_database_impl *impl_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase *iface )
1905 {
1906 return CONTAINING_RECORD(iface, msi_remote_database_impl, IWineMsiRemoteDatabase_iface);
1907 }
1908
1909 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
1910 REFIID riid,LPVOID *ppobj)
1911 {
1912 if( IsEqualCLSID( riid, &IID_IUnknown ) ||
1913 IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
1914 {
1915 IWineMsiRemoteDatabase_AddRef( iface );
1916 *ppobj = iface;
1917 return S_OK;
1918 }
1919
1920 return E_NOINTERFACE;
1921 }
1922
1923 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
1924 {
1925 msi_remote_database_impl* This = impl_from_IWineMsiRemoteDatabase( iface );
1926
1927 return InterlockedIncrement( &This->refs );
1928 }
1929
1930 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
1931 {
1932 msi_remote_database_impl* This = impl_from_IWineMsiRemoteDatabase( iface );
1933 ULONG r;
1934
1935 r = InterlockedDecrement( &This->refs );
1936 if (r == 0)
1937 {
1938 MsiCloseHandle( This->database );
1939 msi_free( This );
1940 }
1941 return r;
1942 }
1943
1944 static HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
1945 LPCWSTR table, MSICONDITION *persistent )
1946 {
1947 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
1948 *persistent = MsiDatabaseIsTablePersistentW(This->database, table);
1949 return S_OK;
1950 }
1951
1952 static HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
1953 LPCWSTR table, MSIHANDLE *keys )
1954 {
1955 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
1956 UINT r = MsiDatabaseGetPrimaryKeysW(This->database, table, keys);
1957 return HRESULT_FROM_WIN32(r);
1958 }
1959
1960 static HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
1961 UINT updatecount, MSIHANDLE *suminfo )
1962 {
1963 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
1964 UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
1965 return HRESULT_FROM_WIN32(r);
1966 }
1967
1968 static HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
1969 LPCWSTR query, MSIHANDLE *view )
1970 {
1971 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
1972 UINT r = MsiDatabaseOpenViewW(This->database, query, view);
1973 return HRESULT_FROM_WIN32(r);
1974 }
1975
1976 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
1977 {
1978 msi_remote_database_impl* This = impl_from_IWineMsiRemoteDatabase( iface );
1979 This->database = handle;
1980 return S_OK;
1981 }
1982
1983 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
1984 {
1985 mrd_QueryInterface,
1986 mrd_AddRef,
1987 mrd_Release,
1988 mrd_IsTablePersistent,
1989 mrd_GetPrimaryKeys,
1990 mrd_GetSummaryInformation,
1991 mrd_OpenView,
1992 mrd_SetMsiHandle,
1993 };
1994
1995 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
1996 {
1997 msi_remote_database_impl *This;
1998
1999 This = msi_alloc( sizeof *This );
2000 if (!This)
2001 return E_OUTOFMEMORY;
2002
2003 This->IWineMsiRemoteDatabase_iface.lpVtbl = &msi_remote_database_vtbl;
2004 This->database = 0;
2005 This->refs = 1;
2006
2007 *ppObj = This;
2008
2009 return S_OK;
2010 }